[英]Bind drag function to object in Tkinter UI
我正在嘗試編寫一個紙牌游戲程序-主要是探索如何使用鼠標在使用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中移動。
問題是您要在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
,您始終可以獲得生成event
的小部件( Canvas
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.