简体   繁体   English

如何处理两个事件循环? Pyrogram 和 Tkinter 的

[英]How to deal with two event loops? Pyrogram's and Tkinter's

I am using Pyrogram and Tkinter:我正在使用 Pyrogram 和 Tkinter:

from tkinter import *
from pyrogram import Client

root = Tk()
app = Client("my_account")

First, I register a handler with Pyrogram:首先,我使用 Pyrogram 注册一个处理程序:

@app.on_message()
def message(client, message):
    print("Message!")

Second, I register a handler with Tkinter:其次,我用 Tkinter 注册了一个处理程序:

def button(event):
    print("Button!")
    
root.bind('<Button>', button)

But how can I start the loops for Pyrogram and Tkinter?但是如何启动 Pyrogram 和 Tkinter 的循环? Obviously the following (or the reverse) does not work:显然以下(或相反)不起作用:

root.mainloop()
app.run()

Edit: Since one of the key feature of Pyrogram is that it is fully asynchronous (eg, https://docs.pyrogram.org/start/updates#registering-a-handler ), I would expect an answer based on Asyncio.编辑:由于 Pyrogram 的一个关键特性是它是完全异步的(例如, https://docs.pyrogram.org/start/updates#registering-a-handler ),我希望得到一个基于 Asyncio 的答案。 Here is however my attempt with threading following comments by @SylvesterKruin.然而,这是我尝试在@SylvesterKruin 的评论之后进行线程化。

t = Thread(target=app.run)
t.start()
root.mainloop()

Il fails with RuntimeError: There is no current event loop in thread 'Thread-1' . Il 失败并出现RuntimeError: There is no current event loop in thread 'Thread-1'

A bit of looking through the pyrogram examples and This answer to prevent blocking.浏览一下热解图示例这个答案以防止阻塞。 I think this might be helpful.我认为这可能会有所帮助。

import asyncio
from pyrogram import Client
import threading

api_id = 12345
api_hash = "0123456789abcdef0123456789abcdef"
app = Client("my_account", api_id, api_hash)

def init_async():
    print('starting')
    loop = asyncio.get_event_loop()  # create loop
    event = asyncio.Event()  # create event
    #new thread to run loop. Prevents tkinter from blocking
    thr = threading.Thread(target=run_main, args=(loop, event))
    thr.start()

def run_main(_loop, _e):
    try:
        _loop.run_until_complete(main())
    finally:
        _loop.close()


async def main():
    async with app:
        await app.send_message("me", "Greetings from **Pyrogram**!")

@app.on_message()
async def message(client, message):
    print("Message!")


root = tk.Tk()
tk.Button(master=root, text='Start Pyrogram', command=init_async).pack()
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM