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

Viewed 562

I am using Pyrogram and Tkinter:

from tkinter import *
from pyrogram import Client

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

First, I register a handler with Pyrogram:

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

Second, I register a handler with Tkinter:

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

But how can I start the loops for Pyrogram and 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 (e.g., https://docs.pyrogram.org/start/updates#registering-a-handler), I would expect an answer based on Asyncio. Here is however my attempt with threading following comments by @SylvesterKruin.

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

Il fails with RuntimeError: There is no current event loop in thread 'Thread-1'.

1 Answers

A bit of looking through the pyrogram examples and This answer to prevent blocking. I think this might be helpful.

import asyncio
import tkinter as tk
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!")

def button(event):
    print("Button!")

root = tk.Tk()
root.bind('<Button>', button)
tk.Button(master=root, text='Start Pyrogram', command=init_async).pack()
root.mainloop()
Related