我一直在使用binance websocket。如果startstop命令在主程序中,工作得很好。现在我想通过GUI来启动和停止socket。所以我把startstop命令放在每个函数中。但这并不奏效。只是在调用函数时没有反应。有什么办法可以解决这个问题吗?
以下是我代码的相关部分(我对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)
我想出了如何做到这一点.启动和停止命令应该是在一个函数。该函数被调用的参数开始或停止.有趣的是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')
我建议不要使用全局变量。
我知道这不是你要的答案,但你可以使用unicorn-binance-websocket-api for python,它已经为你准备好了这些方法。https:/github.comoliver-zehentleitnerunicorn-binance-websocket-api。
这个lib提供了很多例子,而且很容易学习。https:/github.comoliver-zehentleitnerunicorn-binance-websocket-apiblobmasterexample_stream_management_extended.py。