简体   繁体   English

为什么 Tkinter 可执行文件不能捕获组合键?

[英]Why won't Tkinter executable capture key combinations?

I'm building an tkinter app on Python 3.7 and creating an .exe with Pyinstaller 3.5 in Windoows 10. When running the code from the IDE, all intended keyboard commands work as expected.我正在 Python 3.7 上构建一个 tkinter 应用程序,并在 Windows 10 中使用 Pyinstaller 3.5 创建一个 .exe。从 IDE 运行代码时,所有预期的键盘命令都按预期工作。 However, in the executable, key combinations do not work while single key presses are fine.但是,在可执行文件中,组合键不起作用,而单键按下就可以了。

Here is some test code that demonstrates the problem:这是一些演示问题的测试代码:

import tkinter as tk

root = tk.Tk()

txt = tk.StringVar()
lbl = tk.Label(root, textvariable=txt)

def key_handle(event):
    global txt
    txt.set(event.keysym)

def kc_handle(event):
    tk.messagebox.showinfo('Key Combo', 'Key Combo pressed')

root.bind('<Key>', key_handle)
root.bind('<Alt-b>', kc_handle)

lbl.pack()
root.mainloop()

Pyinstaller is then invoked as pyinstaller -w -F key_test.py . Pyinstaller 然后作为pyinstaller -w -F key_test.py被调用。

One thing I do know is that the order of the binds doesn't seem to make a difference.我知道的一件事是绑定的顺序似乎没有什么区别。 How do I get key combinations working in the executable?如何让组合键在可执行文件中工作?

IDLE is built using tkinter and it could import all needed modules for own use and your code could work correctly but when you run it without IDLE then you have to import all modules which you use in code. IDLE是使用tkinter构建的,它可以导入所有需要的模块供自己使用,您的代码可以正常工作,但是当您在没有IDLE情况下运行它时,您必须导入您在代码中使用的所有模块。 In your example it will be在您的示例中,它将是

import tk.messagebox

BTW: Often similar problem is with mainloop() .顺便说一句: mainloop()经常有类似的问题。 IDLE aready runs mainloop() so code may work without own mainloop() . IDLE mainloop()运行mainloop()所以代码可以在没有自己的mainloop()情况下工作。 But normally (without IDLE ) it needs to use mainloop() .但通常(没有IDLE )它需要使用mainloop() It is good to check code in terminal/console/cmd.exe to see if it gives any errors.最好检查terminal/console/cmd.exe代码,看看它是否有任何错误。

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

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