我一直在使用binance websocket。如果启动/停止命令在主程序中,则运行良好。现在我想通过GUI启动和停止套接字。所以我把start/stop命令分别放在一个函数中。但它不起作用。只是在调用函数时没有反应。你知道问题出在哪里吗?
这里是我的代码的相关部分(我是python的新手,欢迎对此代码的任何提示):
def start_websocket(conn_key):
bm.start()
def stop_websocket(conn_key):
bm.close()
def process_message(msg):
currentValues['text']= msg['p']
# --- main ---
PUBLIC = '************************'
SECRET = '************************'
client = Client(api_key=PUBLIC, api_secret=SECRET)
bm = BinanceSocketManager(client)
conn_key = bm.start_trade_socket('BNBBTC', process_message)
# create main window and set its title
root = tk.Tk()
root.title('Websocket')
# create variable for displayed time and use it with Label
label = tk.Label(root)
label.grid(column=5, row=0)
#root.geometry('500x500')
bt_start_socket = tk.Button(root, text="Start Websocket", command=start_websocket(conn_key))
bt_start_socket.grid (column=1, row=1)
bt_stop_socket = tk.Button(root, text="Sop Websocket", command=stop_websocket(conn_key))
bt_stop_socket.grid (column=1, row=10)发布于 2020-04-23 03:49:28
我知道该怎么做了。启动和停止命令应该在一个函数中。使用参数启动或停止来调用该函数。有趣的是,conn_key必须是全球性的。否则,如果再次调用该函数进行关闭,则会打开一个新的Websocket。正如我之前所说的:我对python还很陌生。所以,不能保证这是解决问题的最好方法。它只是起作用了;-)
def start_stop_websocket(switch):
global conn_key
if switch == 'on':
bm.start()
print('started')
if switch == 'off':
bm.stop_socket(conn_key)
bm.close()
print('stoped')发布于 2020-05-02 18:04:02
我建议不要使用全局变量。
我知道这不是您想要的答案,但是您可以使用unicorn-binance-websocket-api for python,它已经为您准备好了这些方法:https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api
该库提供了许多易于学习的示例:https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/example_stream_management_extended.py
https://stackoverflow.com/questions/61195729
复制相似问题