亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:帶有線程的 PubSub 和 WxPython 是否需要 wx.CallAfter?

Python:帶有線程的 PubSub 和 WxPython 是否需要 wx.CallAfter?

楊魅力 2022-10-18 14:53:59
我在用:wxPython 4.0.7.post2Pypubsub 4.0.3Python 3.8.1我有以下我編寫的示例程序:import wximport timefrom threading import Threadfrom pubsub import pubTIME_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()我正在執行沒有 wx.CallAfter 的 pub.sendMessage(TIME_UPDATED, seconds=time_elapsed) ,它似乎工作正常。我不確定為什么。有人可以解釋一下是否需要 wx.CallAfter 嗎?如果是,你能解釋為什么會這樣嗎?是否某些 wx 方法將某些內容放入調度隊列而其他方法沒有?
查看完整描述

1 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

是的,您仍然應該確保 UI 操作發生在 UI 線程上。僅僅因為做某事不安全并不意味著它在某些情況下不能正常工作(或看起來工作正常)。



查看完整回答
反對 回復 2022-10-18
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號