gpt4 book ai didi

python - wx.StaticText线程安全吗?

转载 作者:行者123 更新时间:2023-12-03 13:00:54 25 4
gpt4 key购买 nike

例如,我使用wx.StaticText对象作为计数器,线程安全吗?例如:

class TaskFrame(wx.Frame):
def __init__(self):
self.Counter = wx.StaticText(MainPanel, id = -1, label = "0")

如果我同时在不同线程中为 GetLabel设置 SetLabelself.Counter,会发生什么情况?我会遇到麻烦吗?
Result = self.Counter.GetLabel()
self.Counter.SetLabel(WhateverResult)

最佳答案

它不是线程安全的。引用这个出色的blog post:

In the wxPython world, there are three related “threadsafe” methods. If you do not use one of these three when you go to update your user interface, then you may experience weird issues. Sometimes your GUI will work just fine. Other times, it will crash Python for no apparent reason. Thus the need for the threadsafe methods: wx.PostEvent, wx.CallAfter and wx.CallLater.



简而言之,您可以在发布对象上创建接收方:
from wx.lib.pubsub import Publisher
Publisher().subscribe(update_function, 'update') # Params: callback, event name

然后从线程中使用 CallAfter :
# Will trigger 'update_function' with argument 'My message'
wx.CallAfter(Publisher().sendMessage, 'update', 'My message')

无论如何,如果只想在进程之间共享变量,请使用 supported way of doing this。当前,您正在滥用GUI工具箱来保存变量,而应为此使用内置类型。正确共享它们,并使用GUI显示数据。

关于python - wx.StaticText线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8306735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com