[目前,我正在使用tkinter模块进行Python 3.5 GUI开发。我希望能够将图像从应用程序中的一个位置拖到另一个位置。 tkinter是否支持在应用程序内拖放,如果支持,您如何做?
Drag and Drop in Tkinter?问题是关于在应用程序之间拖放的问题,这不是我在这里问的。
from tkinter import *
root = Tk()
root.geometry("640x480")
canvas = Canvas(root, height=480, width=640, bg="white")
frame = Frame(root, height=480, width=640, bg="white")
frame.propagate(0)
image = PhotoImage(file="C:/Users/Shivam/Pictures/Paint/Body.png")
label = Label(canvas, image=image)
label.pack()
label_2 = Label(frame, text="Drop Here !")
label_2.pack()
label_2.place(x=200, y=225, anchor=CENTER)
canvas.pack(side=LEFT)
frame.pack()
root.mainloop()
Tkinter不直接支持应用程序中的拖放。但是,拖放操作只需要为按钮单击(<ButtonPress-1>
),单击按钮(<B1-Motion>
)和释放按钮(<ButtonRelease-1>
)时移动鼠标进行适当的绑定。 >
这里是一个非常简单的示例,旨在与您的代码一起使用。
首先,我们将创建一个可以管理拖放操作的类。作为类而不是全局函数的集合更容易做到这一点。
class DragManager(): def add_dragable(self, widget): widget.bind("<ButtonPress-1>", self.on_start) widget.bind("<B1-Motion>", self.on_drag) widget.bind("<ButtonRelease-1>", self.on_drop) widget.configure(cursor="hand1") def on_start(self, event): # you could use this method to create a floating window # that represents what is being dragged. pass def on_drag(self, event): # you could use this method to move a floating window that # represents what you're dragging pass def on_drop(self, event): # find the widget under the cursor x,y = event.widget.winfo_pointerxy() target = event.widget.winfo_containing(x,y) try: target.configure(image=event.widget.cget("image")) except: pass
要使用它,您需要做的就是调用
add_draggable
方法,并为其提供要拖动的小部件。
例如:
label = Label(canvas, image=image) ... dnd = DragManager() dnd.add_dragable(label) ... root.mainloop()
这就是基本框架所需要的。由您决定创建一个浮动的可拖动窗口,并突出显示可以放置的项目。
关于相同概念的另一种实现,请参见https://github.com/python/cpython/blob/master/Lib/tkinter/dnd.py
https://github.com/akheron/cpython/blob/master/Lib/tkinter/dnd.py我对其进行了测试,但它似乎仍然可以在python 3.6.1中工作,我建议您对其进行实验并制作为您自己的,因为Tkinter似乎并未正式支持它。