【问题标题】:Python 3.4 / GTK / AsyncPython 3.4 / GTK / 异步
【发布时间】:2019-07-18 16:27:09
【问题描述】:

我使用带有异步功能的 tkinter。

现在我将使用 gtk3 代替 tkinkter。

还有办法运行我的异步函数吗?

我应该如何调整代码

以下是一些代码片段:

async def _event_loop(app, interval=0.05):
    try:
        while True:
            app.update()
            await asyncio.sleep(interval)
    except tkinter.TclError as exc:
        if "application has been destroyed" not in exc.args[0]:
            raise

class SSHFrame(tkinter.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        ...
        ...
    async def _run(self, host, command, user, password):
        try:
            async with asyncssh.connect(host, username=user, password=password,
                                        client_keys=None) as conn:
                self._proc = await conn.create_process(command,
                                                       term_type='dumb')
                while not self._proc.stdout.at_eof():
                    self._output(await self._proc.stdout.read(1024))

                self._output('\n[Disconnected]\n')
        except (asyncssh.Error, OSError) as exc:
            self._output('[%s]\n' % str(exc))
        finally:
            self._proc = None

class App(tkinter.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        ...
        ...

asyncio.get_event_loop().run_until_complete(_event_loop(App(tkinter.Tk())))

【问题讨论】:

    标签: pygtk gtk3 python-asyncio pyobject


    【解决方案1】:
    import asyncio
    import sys
    
    from gi.repository import Gtk, GLib
    
    @asyncio.coroutine
    def start(app):
        yield from asyncio.sleep(0)
        app.register()
        app.activate()
    
    
    def glib_update(main_context, loop):
        while main_context.pending():
            main_context.iteration(False)
        loop.call_later(.01, glib_update, main_context, loop)
    
    
    if sys.platform == "win32":
        from asyncio.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
        asyncio.set_event_loop(loop)
    else:
        loop = asyncio.SelectorEventLoop()
        asyncio.set_event_loop(loop)
    
    # This is just a fake gtk appliaction here, you should create your own see
    # http://python-gtk-3-tutorial.readthedocs.io/en/latest/application.html
    my_gtk_app = Gtk.Application()
    
    try:
        main_context = GLib.MainContext.default()
        asyncio.async(start(my_gtk_app))
        glib_update(main_context, loop)
        loop.run_forever()
    finally:
        loop.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      相关资源
      最近更新 更多