简体   繁体   中英

How can I pass multiple user input values from PySimpleGUI to a function, then output result to PySimpleGUI?

GitHub for this project

I am building a financial trading profit/loss calculator. I have built the script to function in the command line interface (main_cli.py).

Now, I am trying to convert to a desktop GUI via PySimpleGUI, but am having difficulty with passing multiple user input values from PySimpleGUI (main_gui.py) to the calculator function (functions.py), to then output the result in the same PySimpleGUI window.

When I run the main_gui.py script, it still asks for user_input in the CLI.

Just pass values to your function, then convert all fields into your data for the function to calculate the result, and return it back to event loop to update the GUI.

Note: No any entry validation in the code.

import PySimpleGUI as sg

def calculate(values):
    ticker = ticker_list[[values[("Ticker", i)] for i in range(len(tickers))].index(1)]
    tick_size, contract_amount = tickers[ticker]
    position = "Long" if values[("Position", 0)] else "Short"
    purchase_price = float(values['Entry'])
    selling_price  = float(values['Exit'])
    contract_size  = float(values['Contract'])
    tick_value = (((purchase_price - selling_price)*contract_size)/tick_size)
    dollar_value = (tick_value*contract_amount)
    if position == "Long":
        tick_value = abs(tick_value)
        dollar_value = abs(dollar_value)
    return tick_value, dollar_value

tickers = {
    'ES' : (0.25, 12.50),
    'NQ' : (0.25,  5.00),
    'RTY': (0.10,  5.00),
    'YM' : (1.00,  5.00),
    'GC' : (0.10, 10.00),
    'CL' : (0.01, 10.00),
}
ticker_list = list(tickers.keys())
positions = ['Long', 'Short']

keys = {
    'Entry':'Entry price',
    'Exit':'Exit price',
    'Contract':'Contract size',
}

sg.theme('Dark')
sg.set_options(font=('Helvetica', 10))

layout = [
    [sg.Text("Ticker:",   size=10)] + [sg.Radio(tick, "Radio 1", key=("Ticker", i)) for i, tick in enumerate(tickers)],
    [sg.Text("Position:", size=10)] + [sg.Radio(pos,  "Radio 2", key=("Position", i)) for i, pos in enumerate(positions)]] + [
    [sg.Text(text, size=10), sg.InputText(size=10, expand_x=True, key=key)] for key, text in keys.items()] + [
    [sg.Text("Result"), sg.Text(text_color="white", key="Output")],
    [sg.Push(), sg.Button("Reset"), sg.Button("Calculate", button_color=('white', '#007339'))],
]

window = sg.Window('Futures Profit/Loss Calculator', layout=layout)

while True:

    event, values = window.read()
    print(event, values)

    if event == sg.WIN_CLOSED:
        break

    elif event == "Calculate":
        tick_value, dollar_value = calculate(values)
        result = f"ticks: {tick_value} | profit/loss: ${dollar_value}"
        window['Output'].update(result)

    elif event == "Reset":
        for key in keys:
            window[key].update('')

window.close()

在此处输入图像描述

If this function take long time to finish the caluclation, you can call method window.perform_long_operation to run your function, Lambda expression can help to pass the arguments here, then update your GUI when the event '-FUNCTION COMPLETED-' generated, like

    elif event == "Calculate":
        window.perform_long_operation(lambda x=values:calculate(x), '-FUNCTION COMPLETED-')

    elif event == '-FUNCTION COMPLETED-':
        tick_value, dollar_value = values[event]
        result = f"ticks: {tick_value} | profit/loss: ${dollar_value}"
        window['Output'].update(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM