Search code examples
pythonbuttontkinterdrag-and-dropdraggable

Drag and Drop button tkinter python


I'm new using tkinter on python and I would like to develop a program that can Drag and Drop a button pressing other one... I will try to explain : I have button 'A' that will create a new button 'B' and I want to Drag the New button to another place Any help Thanks


Solution

  • The tkinter.dnd module, as suggested by j_4321 in comments.
    Here is some sample code using that library to do what you have said:

    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():
        """Make a new test button."""
        # The functional part of the main window is the canvas.
        Dragable('B').attach(main.canvas)
    
    # Make a button and bind it to our button creating function.
    Button(main.top, text='A', command=make_btn).pack()
    # Start the mainloop.
    mainloop()