我如何运行一个异步循环,同时为 websocket 接收和 tkinter gui 运行一个 while 循环?
我当前的代码:(没有 GUI)
我知道如何为 tkinter gui 编写代码,但在编译时遇到问题。启动 tkinter Mainloop 时,asyncio 循环停止并与 websocket 断开连接。我也尝试过线程,但都没有奏效。
import re
urls = [
'<a href=https://energyplus.net/weather-download/asia_wmo_region_2/IND//IND_Kota.424520_ISHRAE/IND_Kota.424520_ISHRAE.epw>Download Weather File</a>',
'<a href=https://energyplus.net/weather-download/europe_wmo_region_6/ESP//ESP_Alicante.083600_SWEC/ESP_Alicante.083600_SWEC.epw>Download Weather File</a>'
]
for url in urls:
match = re.search(r'href=[\'"]?((?!.*SWEC)[^\'" >]+)', url)
if match:
url = match.group(1)
print(url)
# https://energyplus.net/weather-download/asia_wmo_region_2/IND//IND_Kota.424520_ISHRAE/IND_Kota.424520_ISHRAE.epw
答案 0 :(得分:0)
问题更新:我尝试将 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()
当我按下按钮时,什么也没有发生
答案 1 :(得分:0)
我找到了一个使用线程、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()