Python - Tkinter冻结w / PyHook

时间:2015-09-02 02:19:00

标签: python tkinter

我已经建立了一个计数器,我已经测试过与我玩的另一个游戏一起工作。现在我想利用Tkinter GUI在它增加时显示这个计数器。

我松散地理解在运行PyHook所需的PumpMessages部分的同时从Tkinter运行mainloop存在问题。我已经尝试使用谷歌搜索代码片段进行更正,但我无法找到任何可以插入的内容。

如何更新我的代码,以便Tkinter GUI不会冻结?

import pyHook, pythoncom, sys, win32api, win32con, time, ctypes
from Tkinter import *
from threading import Thread

Fc, JKc = 0, 0
x, j, i = '', '', ''

def killProgram():
    ctypes.windll.user32.PostQuitMessage(0)
    root.destroy()
    rootThread.join()

#this is my counter input
def onKeyboardEvent(event): 
    global i, x, Fc, JKc, j
    i = event.Key
    if i=='F4':
        killProgram
    elif i=='Return':
        if 'f ' == x[:2] and len(x) >= 3:
            Fc = Fc + 1
        elif 'jk ' == x[:3] and len(x) >= 4:
            JKc = JKc + 1
       j = x
        x = ''
    elif i=='Up':
        x = j
    else:
        x = x + chr(event.Ascii)
    return True

hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = onKeyboardEvent
hooks_manager.HookKeyboard()

#My GUI
root = Tk()

wlabel = Label(root, text='Weapon')
wlabel.grid(column=0, row=0, sticky='NE')

hlabel = Label(root, text='Hand')
hlabel.grid(column=1, row=0, sticky='N')

alabel = Label(root, text='All')
alabel.grid(column=2, row=0, sticky='NW')

wc = StringVar()
wcounter = Label(root, textvariable = wc)
wcounter.grid(column=0, row=1, sticky='SE')

hc = StringVar()
hcounter = Label(root, textvariable = hc)
hcounter.grid(column=1, row=1, sticky='S')

ac = StringVar()
acounter = Label(root, textvariable=ac)
acounter.grid(column=2, row=1, sticky='SW')

def startTimerThread():
    while True:
        win32api.PostThreadMessage(mainThreadId, win32con.WM_QUIT, 0, 0)
        time.sleep(1)

mainThreadId = win32api.GetCurrentThreadId()
timerThread = Thread(target=startTimerThread)
timerThread.start()

#Updates Label
while runningProgram:
    hc.set(text=str(Jkc))
    #wc.set(text=str(Fc))
    #ac.set(text=str(Fc+JKc))
    root.after(100,root.quit)
    root.mainloop()
    pythoncom.PumpMessages()

1 个答案:

答案 0 :(得分:0)

您需要在单独的帖子中使用PumpMessages()。此外,除非您希望GUI在启动后不久冻结,否则您希望委派onKeyboardEvent()来创建单个线程,因为该函数需要快速返回TrueFalse尽可能。