将同一小部件​​上的多个事件绑定到同一回调函数

时间:2020-07-26 21:05:29

标签: python-3.x tkinter

看看下面的代码:

import tkinter as tk

class MainApp():
    def __init__(self, parent):
        scr_w = parent.winfo_screenwidth()
        scr_h = parent.winfo_screenheight()
        parent.geometry('{}x{}+{}+{}'.format(1280, 766, scr_w//4, scr_h//4))
        parent.bind('<ButtonPress-1>', self.callback)
        parent.bind('<B1-Motion>', self.callback)
        parent.bind('<ButtonRelease-1>', self.callback)
        parent.bind('<Left>', self.callback)
        parent.bind('<Right>', self.callback)
        parent.bind('<Up>', self.callback)
        parent.bind('<Down>', self.callback)

    def callback(self, e):
        print(e)
        
if __name__ == '__main__':
    root = tk.Tk()
    main = MainApp(root)
    root.mainloop()

我想做的是将 same 小部件的多个不同事件绑定到 same 回调函数。在此示例中,只有三个事件会触发callback(),但请想象一下,在我的真实代码中,我有几个必须触发相同回调函数的键。

是否有一种方法可以在tkinter中使用单个bind()语句,而不是对每个事件都使用单独的bind()语句?

1 个答案:

答案 0 :(得分:2)

按键很容易。您可以绑定到<Any-Keypress>,传递给回调的事件对象可以用于确定按下了哪个键。

您还可以绑定到<Any-ButtonPress>。您将需要对运动事件进行独特的绑定。