使用 Tkinter 进行多线程 [英] Multithreading with Tkinter

查看:145
本文介绍了使用 Tkinter 进行多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用基于 Tkinter 的 GUI 时遇到了一些问题.基本上,GUI 创建了许多线程并运行它们.当每个线程完成时,我希望它更新一个标签以通知用户此特定线程完成.

I'm having some issues with a Tkinter-based GUI. Basically the GUI creates lots of threads and run them. When each thread has finished, I'd like it to update a label to inform the user of this specific thread completion.

我知道 Tkinter 小部件不是线程安全的,并且允许子线程更新视图是一种不好的做法.所以我试图在主线程上触发一个事件,以便它可以更新视图本身.

I know Tkinter widgets are not thread-safe and that it is a bad practice to allow subthreads to update the view. So I'm trying to trigger an event on the main thread so it can update the view itself.

我正在运行下面的简化代码示例:

I'm running the simplified code sample below:

from Tkinter import *
from threading import *

def myClass(root):

   def __init__(self, root):
      self.root = root
      # Other stuff populating the GUI

   # Other methods creating new 'threading.Thread'
   # objects which will call 'trigger_Event'

   # Called by child threads 
   def trigger_Event(self):
      self.root.event_generate("<<myEvent>>", when="tail")

   # Called by main thread
   def processEvent(self):
      # Update GUI label here

if __name__ == '__main__':
   root = Tk()
   root.geometry("500x655+300+300")
   app = myClass(root)
   root.bind("<<myEvent>>", app.processEvent())
   root.mainloop() 

不幸的是,这不起作用:processEvent 从未被调用.我错过了什么?

Unfortunately, this does not work: processEvent is never called. What am I missing ?

推荐答案

root.bind("<<myEvent>>", app.processEvent())

在这里,您将 myEvent 绑定到 app.processEvent 的返回值,因为您正在调用该函数,而不仅仅是引用它.尝试删除括号.

Here, you're binding myEvent to the return value of app.processEvent, because you're calling the function rather than just referring to it. Try removing the parentheses.

root.bind("<<myEvent>>", app.processEvent)

这篇关于使用 Tkinter 进行多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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