4

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

1 Answers1

4

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()
Artemis
  • 2,553
  • 7
  • 21
  • 36
  • Thanks a lot for you help that actually I wanted you save my live you are a hero without cap – Leonardo Radillo escobar Jun 14 '18 at 02:53
  • Would there be a way to do this with buttons that you can also press to run a command? E.X the files on windows desktop can be dragged but also double-clicked to open them. – CodeWizard777 May 05 '22 at 20:31
  • @CodeWizard777 Not using `tkinter.dnd.Icon`, as far as I can tell, but that's only meant for demonstration purposes anyway. See [the source code](https://github.com/akheron/cpython/blob/f91d2f2e2e992c3006a5023eb4ba3cf0d082fde8/Lib/tkinter/dnd.py#L208) for an idea of how to implement your own dragable widget – Artemis May 06 '22 at 18:57