繁体   English   中英

python websocket 客户端与 tkinter。 但不工作的主循环

[英]python websocket client with tkinter. but not working mainloop

我从比特币交易所 WebSocket 收到实时市场价格,并希望在 tkinter 上显示它们。 但是主循环不起作用。 我应该怎么办? 帮助..

import websockets
import json

""" websocket client(real time data receive)"""
async def upbit_client():
    uri = "wss://api.upbit.com/websocket/v1"

    async with websockets.connect(uri, ping_interval=60) as websocket:
        
        subscribe = [{"ticket":"test"}, {"type":"ticker", "codes":["KRW-BTC"], "isOnlyRealtime": True}, {"format":"SIMPLE"}]
        
        subscribe = json.dumps(subscribe) 
        await websocket.send(subscribe)
        
        while True:
            data = await websocket.recv()
            data = json.loads(data)
            print('BTC: ', round(data['tp']), 'percent', round(data['scr']*100, 2), '%')


import tkinter as tk
import asyncio

"""tkinter gui"""
class Win(tk.Tk):
    def __init__(self, loop):
        self.loop = loop
        self.root = tk.Tk() 
        self.root.title("Btc")
        self.root.geometry("640x400+100+100")
        self.root.resizable(False, False)
        self.label = tk.Label(self.root, text="hi.", bg='#fff', fg='#f00',pady=10,padx=10, font=10)
        self.label.pack() 
        self.after(10000, self.loop.run_until_complete(upbit_client())) # working

        self.root.mainloop() # not working
        
        # how to working together?



Win(asyncio.get_event_loop())

无限循环中的 self.after(10000, self.loop.run_until_complete(upbit_client())) 和 self.root.mainloop() 无法运行。

尝试将 tkinter 部分更改为以下内容。

import tkinter as tk
import asyncio

"""tkinter gui"""
class Win(tk.Tk):
    def __init__(self, loop):
        self.loop = loop
        self.title("Btc")
        self.geometry("640x400+100+100")
        self.resizable(False, False)
        self.label = tk.Label(self, text="hi.", bg='#fff', fg='#f00',pady=10,padx=10, font=10)
        self.label.pack() 

app = Win(asyncio.get_event_loop())
app.after(10000, app.loop.run_until_complete(upbit_client()))
app.mainloop()

这应该修复 tkinter 实例化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM