wxPython - 更简单的自定义事件方式?

时间:2015-03-25 20:39:27

标签: user-interface events optimization event-handling wxpython

在我的项目中,我正在使用wxPython并且有许多必须捕获的自定义事件,通常是在变量发生变化时。所以,这就是我设置的方式:

- Event happens (inside a function), it sends a louie signal
- Event Handler catches all event louie signals and performs a func call
- Function call posts the event
- Binding from widget catches it
- Widget sends it to a function in the Event Handler for handling

这似乎是一个非常糟糕的变形。难道不存在简单地捕获绑定中的变量并将其发送到函数的方法吗?我的感觉告诉我,我这一切都错了。有更简单的方法吗?

编辑1:这是我设置的最小,可运行的代码,louie调度是因为线程:

import time
import threading
import wx
from wx.lib.newevent import NewEvent
from louie import dispatcher

customEvent, EVT_CUSTOM_TEST = NewEvent()

def eventFire(changeTo):
    global customEvent
    changerContainer = customEvent(changeTo=changeTo)
    wx.PostEvent(text, changerContainer)

def change(event):
    text.SetLabel(event.changeTo)

class customThread(threading.Thread):

    def __init__(self, group=None, target=None, name=None, verbose=None, **kwargs):
        super(customThread, self).__init__(group=group, target=target, name=name, verbose=verbose)
        self.daemon = True

    def run(self):
        for i in range(10):
            if i == 5:
                dispatcher.send("CHANGE ME", changeTo="Changed Text")
            time.sleep(1)

dispatcher.connect(eventFire, "CHANGE ME")

app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, title="test", size=(100,100))
panel = wx.Panel(frame)
text = wx.StaticText(panel, wx.ID_ANY, "Tester")
frame.Center()
frame.Show()
text.Bind(EVT_CUSTOM_TEST, change)
newThread = customThread()
newThread.start()
app.MainLoop()

编辑2:使用wxPython 2.8.12.1和Ubuntu 14.04

1 个答案:

答案 0 :(得分:2)

您可以在wxPython中使用线程,只需调用线程安全的方法而不是使用调度程序。线程安全的方法是wx.PostEventwx.CallAfter。我喜欢使用pubsub来传递数据。而不是

dispatcher.send("CHANGE ME", changeTo="Changed Text")

我会做类似

的事情
wx.CallAfter(Publisher().sendMessage, "msg_name", "Changed Text")

然后pubsub连接的方法将触发。所以你可以制作一个通用的方法

def change(text):
    text.SetLabel(text)

通过pubsub调用它。以下是一些链接:

请注意,该文章使用wxPython 2.8,而pubsub API在2.9+中更改。所以你可能也想看看这个: