如何制作拖放界面?

2024-04-19 07:11:45 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在使用tkinter模块开发Python 3.5gui。我希望能够将图像从应用程序中的一个位置拖到另一个位置。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()

Tags: 模块image应用程序tkinterrootwidthframelabel
2条回答

https://github.com/akheron/cpython/blob/master/Lib/tkinter/dnd.py
我对它进行了测试,它似乎仍然可以在Python3.6.1中工作,我建议对它进行试验,并使它成为您自己的,因为Tkinter中似乎没有正式支持它。

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

相关问题 更多 >