Python:带线程的PubSub和WxPython是否需要wx.CallAfter?

问题描述 投票:0回答:1

我正在使用:

wxPython 4.0.7.post2

Pypubsub 4.0.3

Python 3.8.1

我有下面编写的示例程序:

import wx
import time
from threading import Thread
from pubsub import pub

TIME_UPDATED = "time.updated"


class MyFrame(wx.Frame):

    def __init__(self):
        super().__init__(parent=None, title="Example")
        self.text = wx.StaticText(self, label="I will display seconds elapsed!")
        self.othertext = wx.StaticText(self, label="I will Update")

        sizer = wx.BoxSizer(orient=wx.VERTICAL)
        sizer.Add(self.text)
        sizer.Add(self.othertext)
        self.SetSizer(sizer)

        self.timer = wx.Timer(self)
        pub.subscribe(self.UpdateTime, TIME_UPDATED)
        self.Bind(wx.EVT_TIMER, self.OnTime, self.timer)
        self.Show()

        self.i = 0
        self.timer.Start(500)

    def OnTime(self, _):
        self.i += 1
        self.othertext.SetLabel(str(self.i))

    def UpdateTime(self, seconds):
        self.text.SetLabel("{seconds} seconds have elapsed".format(seconds=seconds))
        self.text.Refresh()


class BackgroundThread(Thread):

    def run(self):
        time_elapsed = 0
        while True:
            # Lets sleep 1 second
            time.sleep(1)
            time_elapsed += 1
            # <<<<---- This line is what I am worried about.
            pub.sendMessage(TIME_UPDATED, seconds=time_elapsed)


if __name__ == '__main__':

    app = wx.App()
    frame = MyFrame()

    background = BackgroundThread(daemon=True)
    background.start()

    app.MainLoop()

我正在执行pub.sendMessage(TIME_UPDATED,seconds = time_elapsed),而没有wx.CallAfter,它似乎工作正常。我不确定为什么。

有人可以解释一下wx.CallAfter是否再需要了吗?

如果是,您能解释为什么吗?是某些wx方法将某些东西放到了分发队列中,而另一些却没有吗?

python wxpython python-multithreading pypubsub
1个回答
0
投票
是,您仍应确保UI操作在UI线程上进行。仅仅因为做某事不安全并不意味着在某些情况下它不会发生正常工作(或认为工作正常)。
© www.soinside.com 2019 - 2024. All rights reserved.