首页 > 解决方案 > 使用带有参数/条目的 tkinter 按钮打开另一个 python 文件

问题描述

我正在尝试为币安构建一个交易机器人。我已经设法构建了机器人并通过终端使用它。

但是,我想制作一个 GUI,它以与终端中相同的方式运行机器人,除了这次有一个界面。我已经重建了机器人以连接到 binance 数据流以对其进行测试。通过使用各种“代码”(例如 ethusdt、btcusdt),我可以调整机器人以查看特定流以获取价格信息。

现在的问题是我可以使用按钮(链接到bot.py)启动程序,但是启动后我仍然必须在终端中手动输入代码。

所以我的问题是 - 我如何将股票代码作为参数传递给程序,以便它自动启动,而不必在之后输入它?我基本上想在输入字段(ticker_entry)中输入一个代码并将其传递给bot.py代码请求。

这是我编写的代码bot.py

import websocket
import json
import pprint
from colorama import Fore, Back, Style
import numpy as np
import tkinter as tk
tmp = [1]


print("eg. ethusdt = ETH/USDT")
ticker = input(Fore.YELLOW + "Enter ticker here: ")
print(Style.RESET_ALL)


SOCKET="wss://stream.binance.com:9443/ws/"+ ticker +"@kline_1m"




def on_open(ws):
   print('Connection established')

def on_close(ws):
   print("Connection closed")

def on_message(ws, message):

   global tmp
   

   print("waiting for candle to close..")
   
   json_message = json.loads(message)

   

   candle = json_message['k']

   
   is_candle_closed = candle['x']
   close = candle['c']
   
   

   if is_candle_closed:
       
       

       print("\n")
       print(Fore.RED + "Last candle closed at: ")
       print(*tmp, sep= ' , ')
       print(Style.RESET_ALL)
       print("\n")
       print(Fore.GREEN +"New candle closed at: \n{}".format(close))
       print("\n")
       print(Style.RESET_ALL)

       tmp.pop(0)
       tmp.append(float(close))
       
          

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
ws.run_forever()

这是我用tkinter模块编写的代码:

from tkinter import *
from tkinter import filedialog
import os

root = Tk()
WIDTH = 396
HEIGHT = 594
root.title('CheckBot')
root.geometry("396x594")

bg = PhotoImage(file = "rocket.png")

def start_bot(ticker_entry):
    trader = 'bot.py'
    os.system('"%s"' % trader)


#Creating canvas
my_canvas = Canvas(root, width=WIDTH, height=HEIGHT)
my_canvas.pack(fill="both", expand=True)

#Setting image in canvas
my_canvas.create_image(0,0, image=bg, anchor="nw")

#Adding a label

my_canvas.create_text(200,30, text="Enter the ticker to trade", font=("Bembo Bold Italic", 15), fill="#cc5200")

ticker_entry = Entry(my_canvas, bg='white')
ticker.pack(pady=50)

my_canvas.create_text(200,100, text="Enter amount to trade", font=("Bembo Bold Italic", 15), fill="#cc5200")

amount = Entry(my_canvas, bg='white')
amount.pack(pady=10)

trade_button = Button(my_canvas, text='Start trading', bg='#00b359', fg='#000099', command=lambda:start_bot(ticker))
trade_button.pack(pady=70)


root.mainloop()

标签: pythonmultithreadingtkinterbotstrading

解决方案


通常,使用 生成一个全新的 CMD shell 并不是最佳实践,os.system()最好将所有主要功能放在一个函数中,然后导入该函数并调用它。

而不是在tkinter文件中写这个:

def start_bot(ticker_entry):
    trader = 'bot.py'
    os.system('"%s"' % trader)

取逻辑bot.py并将其放入一个函数中,如下所示:

def start_bot(ticker):
    print("eg. ethusdt = ETH/USDT")
    print(Style.RESET_ALL)

    SOCKET="wss://stream.binance.com:9443/ws/"+ ticker +"@kline_1m"

    ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message)
    ws.run_forever()

然后,回到tkinter文件中,您可以简单地使用 导入启动函数from bot import start_bot,并且逻辑应该保持不变。

但是,如果您不想更改代码的任何主要方面,并且想继续os.system()使用一个冗余os.system()调用会浪费更多的 CPU 和 RAM 资源)。

运行文件时,可以在命令行中指定文件参数。这些参数被传递给脚本,但如果不使用它们就不会做任何事情。但是,在您的情况下,由于您想访问它们,您可以这样做:

from sys import argv

# Get the first command line argument
first_argument = argv[1]

# The thing to notice here is that you start from the index 1, since 0 is the script name. (When you run a python script, you are calling the python.exe file, and the script name is the first argument)

这与您的问题有何联系?好吧,既然您已经bot.py在命令行中运行该文件(使用os.system()),您可以添加一个命令行参数来指定代码。然后,bot.py您可以从 获取该股票代码值sys.argv

def start_bot(ticker_entry):
    trader = 'bot.py'
    os.system('"{}" "{}"'.format(trader, ticker_entry)) # Pass the ticker after the script name

并且在bot.py文件中...

from sys import argv
ticker = argv[1]

推荐阅读