Python无法从on_message WebSocket函数内部显示小部件上的数据

jk9hmnmh  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(130)

我成功地检索了数据并使用print显示它,但不知何故,我无法将其加载到表格小部件中。self.ui.tableWidget.setItem(0,1,QTableWidgetItem(current_price))和self.ui.tableWidget.setItem(1,1,QTableWidgetItem(current_price))不显示数据。我不知道我是否做错了什么,我刚开始使用python和websockets

from PySide6.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem

# Important:
# You need to run the following command to generate the ui_form.py file
#     pyside6-uic form.ui -o ui_form.py, or
#     pyside2-uic form.ui -o ui_form.py
from ui_form import Ui_Widget
import websocket
import json

class Widget(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_Widget()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect (self.click_Boton)

    def click_Boton(self) :
        #websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://stream.binance.com:9443/stream?streams=adausdt@ticker/dotusdt@ticker/xrpusdt@ticker/roseusdt@ticker/runeusdt@ticker/avaxusdt@ticker/xlmusdt@ticker/hbarusdt@ticker/fluxusdt@ticker/qntusdt@ticker/linkusdt@ticker", on_message = self.on_message, on_error = self.on_error, on_close = self.on_close)
        #ws.on_open = self.on_open
        #ws.on_message = self.on_message(
        ws.run_forever()
   

    def on_message(self, ws, message):
        data = json.loads(message)
        #print (data)
        current_asset = (data['data']['s'])
        current_price = (data['data']['c'])
        print (current_asset)
        print (current_price)

        if (current_asset == 'ADAUSDT'):
            print ('Asset if ada')
            self.ui.tableWidget.setItem ( 0, 1, QTableWidgetItem(current_price))

        elif (current_asset == 'DOTUSDT'):
            print ('asset if dot')

            self.ui.tableWidget.setItem ( 1, 1, QTableWidgetItem(current_price))

    def on_error(self, ws, error):
        print(error)

    def on_close(self, ws):
            print("WebSocket closed")

    def on_open(self, ws):
        # Subscribe to the real-time price updates for the given symbol
        #symbol = 'btcusdt'
        #ws.send(json.dumps({"method": "SUBSCRIBE", "params": [f"{symbol_2}@ticker"], "id": 1}))
        print ('open')

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = Widget()
    widget.show()
    sys.exit(app.exec())

字符串
我不知道该怎么办,我被困住了

ztyzrc3y

ztyzrc3y1#

我不能运行你的代码,但我认为所有的问题可能是ws.run_forever()永远运行,它阻止了app.exec(),不能更新/重绘窗口中的小部件-所以它不能显示更改,甚至它挂起GUI,因为它不能对buttton的点击等作出React。
通常情况下,它需要在单独的线程中运行websocket,但我发现PyQTQWebSocket,它适合我:

from PySide6.QtWebSockets import QWebSocket
from PySide6.QtCore import QUrl

url = "wss://stream.binance.com:9443/stream?streams=adausdt@ticker/dotusdt@ticker/xrpusdt@ticker/roseusdt@ticker/runeusdt@ticker/avaxusdt@ticker/xlmusdt@ticker/hbarusdt@ticker/fluxusdt@ticker/qntusdt@ticker/linkusdt@ticker"

self.ws = QWebSocket()

self.ws.connected.connect(self.on_open)
self.ws.disconnected.connect(self.on_close)
self.ws.error.connect(self.on_error)

self.ws.textMessageReceived.connect(self.on_message)

self.ws.open(QUrl(url))

字符串
它不需要运行任何run_forever,因为app.exec()可以完成所有任务。
完整的工作代码:
我使用QLabel,因为我没有你的UI文件。
x1c 0d1x的数据

from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
from PySide6.QtWebSockets import QWebSocket
from PySide6.QtCore import QUrl
import json

class Widget(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        
        vbox = QVBoxLayout()        
        
        self.pushButton = QPushButton(self, text='WebSocket')
        self.pushButton.clicked.connect(self.click_Boton)

        self.label1 = QLabel(self, text='Label1: ?')
        
        self.label2 = QLabel(self, text='Label2: ?')
        
        vbox.addWidget(self.pushButton)
        vbox.addWidget(self.label1)
        vbox.addWidget(self.label2)
        
        self.setLayout(vbox)
        
    def click_Boton(self) :
        url = "wss://stream.binance.com:9443/stream?streams=adausdt@ticker/dotusdt@ticker/xrpusdt@ticker/roseusdt@ticker/runeusdt@ticker/avaxusdt@ticker/xlmusdt@ticker/hbarusdt@ticker/fluxusdt@ticker/qntusdt@ticker/linkusdt@ticker"
        
        self.ws = QWebSocket()
        
        self.ws.connected.connect(self.on_open)
        self.ws.disconnected.connect(self.on_close)
        self.ws.error.connect(self.on_error)

        self.ws.textMessageReceived.connect(self.on_message)
        
        self.ws.open(QUrl(url))
        #, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close)
   
    def on_message(self, message):
        print('on_message')
        
        data = json.loads(message)
        #print (data)
        
        current_asset = (data['data']['s'])
        current_price = (data['data']['c'])
        #print(current_asset)
        #print(current_price)

        if current_asset == 'ADAUSDT':
            text = f'ADAUSDT: {current_price}'
            print(text)
            self.label1.setText(text)
            #self.ui.tableWidget.setItem ( 0, 1, QTableWidgetItem(current_price))

        elif current_asset == 'DOTUSDT':
            text = f'DOTUSDT: {current_price}'
            print(text)
            self.label2.setText(text)
            #self.ui.tableWidget.setItem ( 1, 1, QTableWidgetItem(current_price))

    def on_error(self, error):
        print('on_error')
        print(error)

    def on_close(self):
        print("on_close")

    def on_open(self):
        # Subscribe to the real-time price updates for the given symbol
        #symbol = 'btcusdt'
        #ws.send(json.dumps({"method": "SUBSCRIBE", "params": [f"{symbol_2}@ticker"], "id": 1}))
        print('on_open')

if __name__ == "__main__":
    app = QApplication([])
    widget = Widget()
    widget.show()
    app.exec()


我访问过的页面创建答案:

相关问题