Search code examples
pythontkinterdrag-and-drop

How to turn off drag and drop in Tkinter?


I have some code:

from tkinter import *
from tkinter.dnd import Tester as DragWindow, Icon as Dragable

# Make a root window and hide it, since we don't need it.
root = Tk()
root.withdraw()
# Make the actual main window, which can have dragable objects on.
main = DragWindow(root)

def make_btn():
    # The functional part of the main window is the canvas.
    Dragable('B').attach(main.canvas)

def dragoff():
    pass  # What do I write here?

# Make a button and bind it to our button creating function.
B1 = Button(main.top, text='A', command=make_btn)
B1.pack()
B2 = Button(main.top, text='Drag Off', command=dragoff)
B2.pack()

root.mainloop()

I am using tkinter.dnd for the drag and drop feature. But I am having issues turning off the drag-dnd-drop. So, the basic idea, is when I click B1, a Canvas is created with a button where I can move that. When I click B2, I should not be able to drag and drop in the canvas.


Solution

  • First you need to save a reference of the instance of Dragable:

    dragable_item = None
    
    def make_btn():
        global dragable_item
        if dragable_item is None:
            dragable_item = Dragable('B')
            dragable_item.attach(main.canvas)
    

    Then you can call dragable_item.label.unbind("<ButtonPress>") to disable DnD:

    def dragoff():
        if dragable_item:
            dragable_item.label.unbind("<ButtonPress>")