将Tkinter mainloop与另一个事件侦听器组合 [英] Combining Tkinter mainloop with another event listener

查看:146
本文介绍了将Tkinter mainloop与另一个事件侦听器组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个程序,该程序侦听某些按键组合,然后在Tkinter窗口中向用户显示信息.为此,我使用的是这样的按键记录程序(此示例已简化):

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()

如预期的那样,该窗口会弹出并向用户显示他们按下了什么键.但是,我想集成功能以通过与Tkinter窗口进行交互来显示其他消息,例如通过按一个按钮.但是,似乎我需要Tkinter的mainloop来执行此操作,我无法弄清楚如何与PumpMessages()一起运行,因为它还会暂停类似于mainloop()的代码.

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().

我尝试在root.after()中运行root.mainloop(),然后尝试像这样重新创建root.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)

,然后在PumpMessages之前运行它,但是这些解决方案都不起作用.似乎也不能在线程中运行PumpMessages或root.mainloop,尽管我做得不好.如果Tkinter无法做到这一点,那么我是否可以使用其他的Python GUI来使之成为可能?

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?

推荐答案

您无需创建使用mainloop()的函数,只需将mainloop()放在代码底部即可.如果需要延迟,请使用root.after(milliseconds, function)

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)

另外,请记住将mainloop()放在PumpMessages()

例如

def mainloopfunction():
    mainloop()

root.after(5000, mainloopfunction)

希望我能帮上忙!

这篇关于将Tkinter mainloop与另一个事件侦听器组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆