0

I recieve real-time market prices from Bitcoin Exchange WebSocket and want display them on tkinter. But the mainloop doesn't work. What should I do? help..

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())) in infinite loop and self.root.mainloop() cannot run.

leegimoon
  • 1
  • 1
  • You don't need `self.root = tk.Tk()` it's already been defined and try placing `self.root.mainloop()` outside the class. This will require naming your class instance. – Derek Aug 15 '22 at 01:52

1 Answers1

0

Try changing tkinter section to the following.

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()

This should fix the tkinter instantiation.

Derek
  • 1,916
  • 2
  • 5
  • 15
  • I did this and this error occurs. [Previous line repeated 993 more times] RecursionError: maximum recursion depth exceeded – leegimoon Aug 15 '22 at 08:50
  • If I take out `asyncio` references then it just makes a window with a label, so the thinker part works. – Derek Aug 15 '22 at 10:47
  • I'll have to study more. Thank you for your answer. – leegimoon Aug 15 '22 at 11:28
  • I've found a SO question on secure websockets that may help. https://stackoverflow.com/questions/46852066/how-to-create-python-secure-websocket-client-request – Derek Aug 16 '22 at 01:15