简体   繁体   English

无法将热键绑定到具有多个tkinter窗口的脚本

[英]unable to bind hotkeys to script with multiple tkinter windows

from tkinter 
root = Tk()
second_root = Tk()

label_placeholder = Label(root, text='placeholder').grid(row=1, column=0)
second_label_placeholder = Label(second_root, text='placeholder').grid(row=1, column=0)


def saylol(event):
    print('lol')

def sayrofl(event):
    print('rofl')

root.bind_all('<Return>', saylol)
root.mainloop()

second_root.bind_all('<Control-Key-s>', sayrofl)
second_root.mainloop()

Above is just a simplified dummy version of what I'm trying to accomplish. 以上只是我要完成的工作的简化虚拟版本。 I've got a function which creates a new instantiation of tkinter for which I wish to bind a few particular hotkeys to specific functions. 我有一个函数可以创建tkinter的新实例,为此我希望将一些特定的热键绑定到特定的函数。

Now, the first binding works perfectly fine, the problem is that it seems I'm unable to bind a hotkey to the secondary root window. 现在,第一个绑定工作得很好,问题在于,似乎无法将热键绑定到辅助根窗口。

So I was wondering if there is a way around this or is it simply something tkinter is unable to do? 所以我想知道是否有办法解决这个问题,还是tkinter无法做到的事情?

Thanks. 谢谢。

You should not have multiple Tk windows. 您不应有多个Tk窗口。 Tkinter simply isn't designed to work that way. Tkinter根本不是这样设计的。 Tkinter is designed to have exactly one root window, and one call to mainloop() for the life of the program. Tkinter设计为仅具有一个根窗口,并且在程序生命周期内mainloop()进行一次调用。 You can violate those constraints if you have a solid understanding of how tkinter works, but there's rarely a good reason to do so. 如果您对tkinter的工作原理有深入的了解,则可以违反这些限制,但是很少有充分的理由这样做。

If you need more than the root window, create instances of Toplevel 如果您需要的不仅仅是根窗口,请创建Toplevel实例

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

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