【问题标题】:Bind drag function to object in Tkinter UI将拖动功能绑定到 Tkinter UI 中的对象
【发布时间】: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 周围移动。

【问题讨论】:

    标签: python tkinter drag


    【解决方案1】:

    问题是您在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)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 2013-09-10
      • 2013-05-29
      • 2012-02-22
      • 1970-01-01
      相关资源
      最近更新 更多