[英]Python - Run telethon alongside Tkinter GUI
I'm looking to make a GUI telethon login and event listener using tkinter, but the GUI freeze when working with telethon, so I tried to use thread the first button is 'connect' which is connecting to telegram account, and 'send' button to start an event listening when a new message arrive but it's not working.我正在寻找使用 tkinter 制作 GUI Telethon 登录和事件侦听器,但是使用 Telethon 时 GUI 冻结,所以我尝试使用线程第一个按钮是连接到电报帐户的“连接”和“发送”按钮当有新消息到达但它不起作用时开始监听事件。
This is what I tried这是我尝试过的
root = tkinter.Tk()
root.geometry("200x100")
def refresh():
print("update")
root.update()
root.after(1000, refresh)
def connect():
global client
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
client = TelegramClient(phone, api_id, api_hash, flood_sleep_threshold=3)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
try:
client.sign_in(phone, code=input(f'Enter the code: {phone} : '))
except SessionPasswordNeededError:
password = input("Enter 2fa password : ")
client.sign_in(password=password)
print(client.get_me())
async def handler(event):
print(event)
def send():
client.add_event_handler(handler, events.NewMessage)
client.run_until_disconnected()
def click():
print("Clicked!")
B = tkinter.Button(root, text="Connect", command=lambda: threading.Thread(target=connect).start())
B.pack()
BB = tkinter.Button(root, text="Send", command=lambda: threading.Thread(target=send).start())
BB.pack()
C = tkinter.Button(root, text="Hello", command=click)
C.pack()
refresh()
root.mainloop()
I've got the following error message when 'send' button pressed RuntimeError: There is no current event loop in thread 'Thread-2'.
按下“发送”按钮时出现以下错误消息RuntimeError: There is no current event loop in thread 'Thread-2'.
Tkinter does not really support asyncio
, however, there are workarounds (I recommend you check the linked example in full): Tkinter 并不真正支持asyncio
,但是, 有一些解决方法(我建议您完整查看链接示例):
async def main(interval=0.05):
client = TelegramClient(SESSION, API_ID, API_HASH)
try:
await client.connect()
except Exception as e:
print('Failed to connect', e, file=sys.stderr)
return
app = App(client)
try:
while True:
# We want to update the application but get back
# to asyncio's event loop. For this we sleep a
# short time so the event loop can run.
#
# https://www.reddit.com/r/Python/comments/33ecpl
app.update()
await asyncio.sleep(interval)
except KeyboardInterrupt:
pass
except tkinter.TclError as e:
if 'application has been destroyed' not in e.args[0]:
raise
finally:
await app.cl.disconnect()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.