Telethon异步功能到Tkinter按钮

时间:2020-06-01 02:50:35

标签: python bots telegram telethon

我下面有这个异步函数,基本上我想使用tkinter将它放在按钮的命令中。

async def main():
    await client.send_message('username', 'message')

with client:
    client.loop.run_until_complete(main())

message中,我想将代码的变量cpf放进去,但是我不知道到底该如何将它们放在一起。我是python的新手,所以对不起任何错...

上面的代码是我的尝试方式,但是它只是在运行代码时才运行函数,而不是在按下Button时才运行。我得到ValueError: The message cannot be empty unless a file is provided

from telethon import TelegramClient, events, sync
from tkinter import *

api_id = xxxxx
api_hash = 'xxxxxx'

client = TelegramClient('session_name', api_id, api_hash)
client.start()

root = Tk()

canvas = Canvas(root)
canvas.pack()

code_entry = Entry(canvas)
code_entry.pack()

async def main():
    cpf = code_entry.get()
    await client.send_message('ConsignadoBot', cpf)

with client:
    client.loop.run_until_complete(main)

search_btn = Button(canvas, text='Consultar', command=main)
search_btn.pack()

root.mainloop()

1 个答案:

答案 0 :(得分:1)

您的代码在产生您声称拥有的代码之前会产生完全不同的错误。

with client:
    client.loop.run_until_complete(main)

此行失败,因为在loop.run_until_complete()中,“ asyncio.Future中需要一个协程或一个等待的程序”:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 558, in run_until_complete
    future = tasks.ensure_future(future, loop=self)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 619, in ensure_future
    raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required

正确的代码是:

with client:
    client.loop.run_until_complete(main())

现在,它将以“空消息”出现错误,因为它是在用户输入任何内容之前执行的。


此代码:

root.mainloop()

正在阻止。 Telethon是asyncio库,这意味着除非您执行其他操作,否则事件循环将不会运行,这意味着Telethon将无法取得任何进展。

这可以通过使其异步来解决:

async def main(interval=0.05):
    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
            root.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 client.disconnect()

client.loop.run_until_complete(main())

有关更加精心设计的async友好型tkinter应用程序,请参见Telethon's gui.py example