gpt4 book ai didi

python - 将拖动功能绑定(bind)到 Tkinter UI 中的对象

转载 作者:行者123 更新时间:2023-12-01 02:49:58 25 4
gpt4 key购买 nike

我正在尝试编写一个纸牌游戏程序 - 主要是探索如何使用 Tkinter 在 GUI 中使用鼠标移动对象。我发现以下代码允许用户使用鼠标在窗口中移动卡片:

from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'green4')

def drag(event):
card.place(x=event.x_root, y=event.y_root,anchor=CENTER)

card = Canvas(window, width=74, height=97, bg='blue')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)

window.mainloop()

但是,如果我添加另一张卡,如下所示:

another_card = Canvas(window, width=74, height=97, bg='red')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)

点击这张卡只会移动第一张卡。当我尝试修改拖动功能时,如:

def drag(event, card):
card.place(x=event.x_root, y=event.y_root,anchor=CENTER)

another_card.bind("<B1-Motion>", drag(event, another_card))

我收到“参数太多”或“名称“事件”未定义”错误。由于我最终将在屏幕上显示多达 52 张卡片,因此我无法为每张卡片编写单独的拖动函数。是否可以编写可以绑定(bind)到任何对象的通用“拖动”代码?

PS 在这个例子中我刚刚使用了空白 Canvas 。不过,我有 52 张扑克牌的 gif,我希望(希望)能够在游戏本身的 GUI 中移动它们。

最佳答案

问题在于您正在硬编码对 drag() 函数中第一张卡的引用。

from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'green4')

def drag(event):
event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)

card = Canvas(window, width=74, height=97, bg='blue')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)

another_card = Canvas(window, width=74, height=97, bg='red')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)

window.mainloop()

通过使用event.widget,您始终可以获得生成事件的小部件(Canvas)。

关于python - 将拖动功能绑定(bind)到 Tkinter UI 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44902846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com