【发布时间】:2017-12-07 17:48:42
【问题描述】:
我正在尝试编写一个纸牌游戏程序 - 主要是为了探索如何使用鼠标在使用 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 张卡片,因此我无法为每张卡片编写单独的拖动功能。是否可以编写可以绑定到任何对象的通用“拖动”代码?
PS 在这个例子中我刚刚使用了一个空白画布。不过,我有 52 张扑克牌的 GIF,我将(希望)在游戏本身的 GUI 周围移动。
【问题讨论】: