简体   繁体   English

Tkinter:将相同的键绑定到不同的小部件

[英]Tkinter: binding the same key to different widgets

Is there a way to bind the same key to two different widgets in Tkinter? 有没有办法将相同的键绑定到Tkinter中的两个不同的小部件?

regards, 问候,

jacopo 雅格布

Sure there is. 当然有。 Just bind it to two different widgets. 只需将其绑定到两个不同的小部件即可。

import Tkinter
root = Tkinter.Tk()

def keypress1(event):
    print event.keysym, " key pressed in root"

def keypress2(event):
    print event.keysym, " key pressed in text"

text = Tkinter.Text(root, width=20, height=20)
root.bind("<Return>", keypress1)
text.bind("<Return>", keypress2)
text.pack()

root.mainloop()

Of course, the event has to actually occur in both widgets. 当然,事件必须实际发生在两个小部件中。 I'm not sure whether there's a way to propagate an event captured by one widget to another that didn't capture it. 我不确定是否有办法将一个小部件捕获的事件传播到另一个没有捕获它的事件。 But there are probably better ways to solve your problem than propagating events that way; 但是,解决问题的方法可能比传播事件的方式更好; you can always catch the event in root and do whatever you want there. 你总是可以在root捕获事件并在那里做你想做的事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM