程序在后台运行时应该能够检测键盘输入。 TKinker为gui运行了另一个循环。
我尝试使用来自Tkinker的事件,但是这些事件仅在gui窗口聚焦时才起作用。线程化是我的第二次尝试,但是键盘监听程序仅在gui关闭后才运行。
from pynput.keyboard import Key, Controller, Listener
from threading import *
[...]
keyboard = Controller()
#gui display and listener
def gui():
window.mainloop()
#keyboard listener
def keyboardlistener():
with Listener(on_release=on_release) as listener:
listener.join()
thread1 = Thread(target = gui)
thread2 = Thread(target = keyboardlistener)
thread1.start()
thread2.start()
# Do work indepedent of loopA and loopB
thread1.join()
thread2.join()
将侦听器放在第一个线程中时,我得到了RuntimeError: Calling Tcl from different appartment
。