[英]Running asyncio loop and tkinter gui
如何运行异步循环,同时为 websocket 接收和 tkinter gui 运行 while 循环?
我当前的代码:(没有 GUI)
我知道如何为 tkinter gui 编写代码,但在编译它们时会遇到问题。 启动 tkinter Mainloop 时,asyncio 循环停止并与 websocket 断开连接。 我也尝试过线程,但也没有奏效。
import asyncio
import websockets
from aioconsole import ainput
queue = asyncio.Queue()
async def connect():
global name
try:
async with websockets.connect("ws://ip:port") as websocket:
print("Verbunden!")
asyncio.get_running_loop().create_task(send(websocket))
asyncio.get_running_loop().create_task(cli())
while True:
message = await websocket.recv()
print(message)
except:
print("Fehler!")
await asyncio.sleep(2)
asyncio.get_running_loop().stop()
async def send(websocket):
print("Sender gestartet!")
global name
while True:
message = await queue.get()
await websocket.send(message)
async def cli():
print("Bereit für Eingabe!")
while True:
message = await ainput()
await queue.put(message)
loop = asyncio.get_event_loop()
loop.create_task(connect())
loop.run_forever()
问题更新:我尝试将 asyncio 和 tkinter 与 thrading 结合使用
它有点混搭
import asyncio
import threading
import tkinter
event = None
async def start(queue):
event = asyncio.Event()
tkinter.Button(text="Button", command=button(queue)).pack()
queue.clear()
while True:
await queue.wait()
#await asyncio.sleep(1)
print("test")
queue.clear()
async def gui():
win.mainloop()
def start_loop():
global loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(start(event))
loop.run_forever()
threading.Thread(target=start_loop).start()
def button(queue):
print("button")
global loop
asyncio.run_coroutine_threadsafe(loop=loop, coro=que(queue))
async def que(event):
print("que")
await event.set()
win = tkinter.Tk()
win.mainloop()
当我按下按钮时,什么也没有发生
我找到了一个使用线程、asyncio 和 websockets 的工作解决方案:
import tkinter
import asyncio
import threading
import websockets
from websockets import exceptions
import json
from datetime import datetime
# Starthilfe für asynkrone Funktion connect
def _asyncio_thread():
async_loop.create_task(connect())
async_loop.run_forever()
async def connect():
try:
async with websockets.connect("ws://194.163.132.218:8765") as websocket:
while True:
message = await websocket.recv()
print(message)
async def send(websocket, name):
while True:
message = await queue.get()
await websocket.send(msg)
def buttonexecutor(e=None):
msg = entry.get()
asyncio.run_coroutine_threadsafe(messagesender(msg), async_loop)
entry.delete(0, "end")
async def messagesender(message):
await queue.put(message)
def logger(reason, message):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
text.configure(state="normal")
text.insert("end", f"({current_time}) [ {reason} ] {message}\n")
text.configure(state="disabled")
if __name__ == '__main__':
# Asyncio
async_loop = asyncio.get_event_loop()
queue = asyncio.Queue()
# Erstelle tkinter
root = tkinter.Tk()
root.title("Messanger")
text = tkinter.Text(root, width=150, state="disabled")
text.pack()
entry = tkinter.Entry(root, state="disabled", width=100)
entry.pack()
tkinter.Button(master=root, text="Senden", command=buttonexecutor).pack()
# Starte Websocket Verbindung
thread = threading.Thread(target=_asyncio_thread).start()
# Starte tkinter
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.