1

我有一个 Tkinter GUI 应用程序,我需要在按钮按下时隐藏它。我不能假设应用程序会有焦点,所以我实现了 pyHook,键盘记录器样式。但是,每当我从 pyHook 启动的函数中调用withdraw() 时,窗口就会挂起,我必须强制关闭它。

为了测试,我在 GUI 内部添加了一个按钮来调用完全相同的函数,它工作得很好。这是怎么回事?'hiding' 打印了两次,所以我知道它真的挂在withdraw() 调用本身上。

下面是一个最小的完整可验证示例来说明我的意思:

from Tkinter import *
import threading
import time

try:
    import pythoncom, pyHook
except ImportError:
    print 'The pythoncom or pyHook modules are not installed.'

# main gui box
class TestingGUI:
    def __init__(self, root):

        self.root = root
        self.root.title('TestingGUI')

        self.button = Button(root, text="Withdraw", command=self.Hide) # works fine
        self.button.grid()

    def ButtonPress(self, scancode, ascii):
        if scancode == 82:   # kp_0
            self.Hide() # hangs

    def Hide(self):
        print 'hiding'
        self.root.withdraw()
        time.sleep(2)
        self.root.deiconify()

root = Tk()
TestingGUI = TestingGUI(root)

def keypressed(event):
    key = chr(event.Ascii)
    # have to start thread in order to return True as required by pyHook
    threading.Thread(target=TestingGUI.ButtonPress, args=(event.ScanCode,key)).start()
    return True

def startlogger():
    obj = pyHook.HookManager()
    obj.KeyDown = keypressed
    obj.HookKeyboard()
    pythoncom.PumpMessages()

# need this to run at the same time
logger = threading.Thread(target=startlogger)
# quits on main program exit
logger.daemon = True
logger.start()

# main gui loop
root.mainloop()
4

1 回答 1

1

根据此处的答案解决:

本质上,Tkinter 类中负责处理按键的函数ButtonPress,不能从另一个线程调用。

于 2016-06-21T13:17:54.830 回答