簡體   English   中英

運行 asyncio 循環和 tkinter gui

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM