Multithreading with Tkinter

雨燕双飞 提交于 2019-12-11 21:03:28

问题


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.

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

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


回答1:


root.bind("<<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)


来源:https://stackoverflow.com/questions/26161635/multithreading-with-tkinter

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