问题描述
例如:
class DemoFrame(wx.Frame):
def __init__(self):
Initializing
...
self.TextA = wx.StaticText(MainPanel, id = -1, label = "TextAOrWhatever")
self.TextB = wx.StaticText(MainPanel, id = -1, label = "TextBOrWhatever")
...
def StaticTextUpdating(self, ObjectName, Message):
ObjectName.SetLabel(Message)
def WorkerA(self):
while True:
Work on something
UpdatingThread = threading.Thread(target = self.StaticTextUpdating, args = (self.TextA, "Something for TextA", ))
UpdatingThread.start()
time.sleep(randomSecs)
def WorkerB(self):
while True:
Work on something
UpdatingThread = threading.Thread(target = self.StaticTextUpdating, args = (self.TextB, "Something for TextB", ))
UpdatingThread.start()
time.sleep(randomSecs)
...
def StartWorking(self):
Spawn WorkerA thread
Spawn WorkerB thread
...
如您所见,我总是在新线程中更新StaticText
,并且我100%确定在某个特定时间点只有一个线程在更新特定对象,但是问题是,时不时地运行一会儿,一些物体就消失了.为什么会这样呢?这是否意味着GUI更新不是线程安全的?也许在某个时间点只能更新一个对象?
As you can see, I always update StaticText
in new threads, and I'm 100% sure at a whatever certain time point there's only one thread updating a specific object, but the problem is, every now and then after running for a while, some objects just disappear. Why is this happening? Does it mean GUI updating is not thread safe? Maybe only one object can be updated at a certain time point?
已添加:
好的,wx.CallAfter应该是上述代码的一个很好的解决方案.但是我还有另一个问题,如果按钮事件和SetLabel
同时发生怎么办?尽管我什么都没看到,这样的事情不会引起麻烦吗?
OK, wx.CallAfter should be a good solution for above codes. But I got another question, what if a button event and SetLabel
happens at the same time? Wouldn't things like this cause troubles although I don't see any?
推荐答案
大多数wx方法都不是线程安全的.如果要从另一个线程调用wx方法,请使用wx.CallAfter.替换
Most wx methods are not thread-safe. Use wx.CallAfter if you want to invoke a wx method from another thread; replace
ObjectName.SetLabel(Message)
具有:
wx.CallAfter(ObjectName.SetLabel, Message)
一些背景信息
在wx(以及大多数其他UI平台)中,所有UI更新都在称为主线程(或UI线程)的单个线程中执行.这样可以避免线程同步对性能的影响,从而使UI更快地工作.
In wx (And in most other UI platforms) all the UI updates get executed in a single thread called main thread (Or UI Thread). This is to make the UI work faster by avoiding the performance hit of thread synchronization.
但是,这样做的缺点是,如果我们编写代码以从其他线程更新UI,则结果是不确定的.有时可能会起作用,有时可能会崩溃,有时可能会发生其他事情.因此,我们应该始终转到UI线程进行UI更新.因此,我们使用CallAfter函数使UI更新函数在UI线程中执行.
But the down side of this is that If we write code to update the UI from a different thread the results are undefined. Sometimes it may work, sometimes it may crash, sometimes some other thing may happen. So we should always go to UI thread to do the UI updates. So we use CallAfter function to make UI update function execute in the UI thread.
这篇关于仅仅使用线程来更新GUI还是不够吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!