🥑wxPython异步等待示例
wxPython | 异步等待 | 事件循环
方式一:
混合事件循环
将 wxPython 事件循环与 Python 3 的 asyncio 循环混合在一起。该库每 20 毫秒轮询一次 UI 消息,并在其余时间运行异步消息循环。空闲时,CPU 使用率在 Windows 上为 0%,在 MacOS 上约为 1-2%。
导入库
使用
使用 AsyncBind 或 StartCoroutine 启动的任何协程都附加到 wx.Window。当Window被销毁时,它会自动取消。这使得它更易于使用,因为您无需亲自取消它们。要显示对话框,请使用 AsyncShowDialog 或 AsyncShowDialogModal。这允许使用“await”等待对话框完成。不要直接使用 dlg.ShowModal(),因为它会阻止事件循环。
代码片段:
class TestFrame(wx.Frame):
    def __init__(self, parent=None):
        super(TestFrame, self).__init__(parent)
        vbox = wx.BoxSizer(wx.VERTICAL)
        button1 =  wx.Button(self, label="Submit")
        self.edit =  wx.StaticText(self, style=wx.ALIGN_CENTRE_HORIZONTAL|wx.ST_NO_AUTORESIZE)
        self.edit_timer =  wx.StaticText(self, style=wx.ALIGN_CENTRE_HORIZONTAL|wx.ST_NO_AUTORESIZE)
        vbox.Add(button1, 2, wx.EXPAND|wx.ALL)
        vbox.AddStretchSpacer(1)
        vbox.Add(self.edit, 1, wx.EXPAND|wx.ALL)
        vbox.Add(self.edit_timer, 1, wx.EXPAND|wx.ALL)
        self.SetSizer(vbox)
        self.Layout()
        AsyncBind(wx.EVT_BUTTON, self.async_callback, button1)
        StartCoroutine(self.update_clock, self)
        
    async def async_callback(self, event):
        self.edit.SetLabel("Button clicked")
        await asyncio.sleep(1)
        self.edit.SetLabel("Working")
        await asyncio.sleep(1)
        self.edit.SetLabel("Completed")
    async def update_clock(self):
        while True:
            self.edit_timer.SetLabel(time.strftime('%H:%M:%S'))
            await asyncio.sleep(0.5)源代码
方式二
源代码
Last updated
Was this helpful?
