And*_*y G 3 python tkinter drag
我正在尝试编写一个纸牌游戏程序 - 主要是探索如何使用 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()
Run Code Online (Sandbox Code Playgroud)
但是,如果我添加另一张卡,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
单击这张卡只会移动第一张卡。当我尝试修改拖动功能时,如下所示:
def drag(event, card):
card.place(x=event.x_root, y=event.y_root,anchor=CENTER)
Run Code Online (Sandbox Code Playgroud)
和
another_card.bind("<B1-Motion>", drag(event, another_card))
Run Code Online (Sandbox Code Playgroud)
我收到“参数太多”或“名称“事件”未定义”错误。由于我最终将在屏幕上显示多达 52 张卡片,因此我无法为每张卡片编写单独的拖动函数。是否可以编写可以绑定到任何对象的通用“拖动”代码?
PS 在这个例子中我刚刚使用了空白画布。不过,我有 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()
Run Code Online (Sandbox Code Playgroud)
通过使用event.widget,您总是可以获得Canvas生成event.
| 归档时间: |
|
| 查看次数: |
6210 次 |
| 最近记录: |