Combining Tkinter mainloop with another event listener

走远了吗. 提交于 2019-12-08 05:40:01

问题


I am trying to build a program that listens for certain key combinations and then shows information to the user in a Tkinter window. To do this, I'm using a keylogger like so (simplified for this example):

from pyHook import HookManager
from pythoncom import PumpMessages
import Tkinter as tk

def on_keyboard_event(event):
    label.config(text=event.Key)
    root.update()
    return True

hm = HookManager()
hm.KeyDown = on_keyboard_event
hm.HookKeyboard()
root = tk.Tk()
label = tk.Label(root, text='Hello world')
label.pack()
PumpMessages()

As expected, the window pops up and shows the user what key they pressed. However, I would like to integrate functionality to show other messages by interacting with the Tkinter window, such as by pressing a button. However, it seems I need Tkinter's mainloop to do this, which I can't figure out how to run alongside PumpMessages(), since it also halts the code similar to mainloop().

I tried running root.mainloop() in a root.after(), and I tried recreating root.mainloop like so:

def mainloop():
    root.update()
    root.after(50, mainloop)

and then running it right before PumpMessages, but neither of these solutions worked. It also doesn't seem like you can run PumpMessages or root.mainloop in a thread, though I could just not be doing it right. If this is not possible with Tkinter, is there an alternate Python GUI I could use that would make it possible?


回答1:


You don't need to create a function to use mainloop() so just simply place the mainloop() at the bottom of your code. If you want a delay on it, use root.after(milliseconds, function)

Also, remember to put mainloop() before PumpMessages()

e.g.

def mainloopfunction():
    mainloop()

root.after(5000, mainloopfunction)

Hope I could help!



来源:https://stackoverflow.com/questions/42101906/combining-tkinter-mainloop-with-another-event-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!