簡體   English   中英

為什么我在使用 PySimpleGUI 的 while 循環中對列表框的更新最終導致我的程序掛起?

[英]Why does my update to a Listbox in a while loop with PySimpleGUI end up in my program hanging?

所以,我正在構建一個小 Python 程序來為我做一些成本和吞吐量計算。 請記住,我是 Python 新手,並且對這個項目的 PySimpleGUI 完全陌生。 我特別關心為什么在下面的代碼中,第 59 行( update_values()函數中的thruput_window['LISTBOX'].update(prompt) )導致程序掛起? 我認為它應該使用指示的字符串更新,並繼續通過 while 循環,但它只是停止,甚至不使用prompt更新 Listbox 元素。 有任何想法嗎?

感謝您的幫助,並為長代碼塊道歉; 我不經常在這里發帖,也不確定要包含多少,所以我只是發布了整個內容。

# Throughput & Cost of Ownership Calculations
# Import necessary libraries
import PySimpleGUI as sg


# Define functions
def import_values():
    mylines = []
    myvalues = []
    with open(r'throughput_variables.txt', 'r') as file:
        for myline in file:
            mylines.append(myline.rstrip('\n'))
    for element in mylines:
        start = element.find(':') + 2
        end = len(element)
        value = int(element[start:end])
        myvalues.append(value)
    return myvalues


def import_variables():
    mylines = []
    myvariables = []
    with open(r'throughput_variables.txt', 'r') as file:
        for myline in file:
            mylines.append(myline.rstrip('\n'))
    for element in mylines:
        variable = element[:element.find(':')]
        myvariables.append(variable)
    return myvariables


def display_file():
    mylines = []
    myfile = []
    with open(r'throughput_variables.txt', 'r') as file:
        for myline in file:
            mylines.append(myline.rstrip('\n'))
    for element in mylines:
        myfile.append(element)
    return myfile


def update_values():
    Qtable1 = "What is the total recipe 1 time? \n"
    Qtable2 = "What is the total recipe 2 time? \n"
    Qtable3 = "What is the total recipe 3 time? \n"
    Qcleaner = "What is the total recipe time for the cleaner? \n"
    Qwts4 = "How long does it take to unload? \n"
    Qwetbot = "How long does it take the robot to handle? \n"
    myprompts = [Qtable1, Qtable2, Qtable3, Qcleaner, Qwts4, Qwetbot]
    myvariables = import_variables()
    myvalues = ['','','','','','']
    k = 0
    thruput_window['USER-INPUT'].bind('<Return>', '_Enter')
    with open(r'throughput_variables.txt', 'w+') as file:
        while k < 6:
            prompt = [myprompts[k]]
            thruput_window['LISTBOX'].update(prompt)
            if thruputEvent == 'USER-INPUT' and '_Enter':
                myvalues.append(thruputValues['USER-INPUT'])
                thruput_window['LISTBOX'].update([prompt[k],myvalues[k]])
                file.write(myvariables[k] + ": " + myvalues[k] + "\n")
                k = k + 1
    return import_values()


def calc_thruput(myvalues):
    t1_time = myvalues[0]
    t2_time = myvalues[1]
    t3_time = myvalues[2]
    cleaner_time = myvalues[3]
    wts4_transfer_time = myvalues[4]
    wet_bot_time = myvalues[5]
    denominator = max(t1_time, t2_time, t3_time) - min(t1_time, t2_time, t3_time) + \
                  max(t3_time, cleaner_time) + wts4_transfer_time + wet_bot_time
    numerator = 3600
    thruput = numerator / denominator
    return round(thruput, 2)


# Setup the home screen GUI
sg.theme('Dark2')
fnt = ('Gadugi', 20)
layout = [[sg.Text("What would you like to calculate? \n", font=('Gadugi', 40))],
          [sg.Button("Cost of Ownership")],
          [sg.Button("Throughput")],
          [sg.Button("Exit")]]
# Create the window
main_window = sg.Window("Operations Estimations", layout, margins=(400, 250), font=fnt)

# Create an event loop
while True:
    event, values = main_window.read()
    if event == "Throughput":
        with open(r'throughput_variables.txt', 'r') as file:
            content = display_file()
        layout = [[sg.Text("Do these times look correct, or would you like to append? ", font=('Gadugi', 30))],
                  [sg.Text("All times are in seconds. ", font=fnt)],
                  [sg.Listbox(values=content, size=(70, 10), key='LISTBOX')],
                  [sg.Input(size=(25, 1), enable_events=True, key='USER-INPUT')],
                  [sg.Button("Correct")],
                  [sg.Button("Append")],
                  [sg.Button("Go Back")]]
        thruput_window = sg.Window("Throughput Calculator", layout, margins=(325, 150), font=fnt)

        while True:
            thruputEvent, thruputValues = thruput_window.read()

            if thruputEvent == "Correct":
                answer = ["Throughput = ", str(calc_thruput(import_values())) + " microns/hour"]
                thruput_window['LISTBOX'].update(answer)
            if thruputEvent == "Append":
                answer = ["Throughput = ", str(calc_thruput(update_values())) + " microns/hour"]
                thruput_window['LISTBOX'].update(answer)
            elif thruputEvent == "Go Back" or event == sg.WIN_CLOSED:
                break
        thruput_window.close()
    # End program if user presses Exit or closes the window
    if event == "Exit" or event == sg.WIN_CLOSED:
        break
main_window.close()

update_values在 thruput_window 的“追加”事件中調用。

在 function update_values ,你做錯了什么

  • 將返回鍵綁定到元素'USER-INPUT' ,綁定應該在 thruput_window 完成后立即完成,然后循環讀取事件。
thruput_window = sg.Window("Throughput Calculator", layout, margins=(325, 150), font=fnt, finalize=True)    # Add option `finalize=True`
thruput_window['USER-INPUT'].bind('<Return>', '_Enter')
  • 一次又一次地更新元素,最好更新一次。 包括 thruput_window 的“追加”事件中的更新,總共 13 次,但只顯示最后一次。
    with open(r'throughput_variables.txt', 'w+') as file:
        while k < 6:
            prompt = [myprompts[k]]
            thruput_window['LISTBOX'].update(prompt)
            if thruputEvent == 'USER-INPUT' and '_Enter':
                myvalues.append(thruputValues['USER-INPUT'])
                thruput_window['LISTBOX'].update([prompt[k],myvalues[k]])
                file.write(myvariables[k] + ": " + myvalues[k] + "\n")
                k = k + 1
  • 錯誤的事件處理,它在事件“追加”下,所以跟隨 if 將始終為 False。 它應該在 thruput_window 的 while 循環中,所以一個新的 thruput_window.read() 來獲取事件,沒有read ,沒有新的 thruputEvent 和 thruputValues。
if thruputEvent == 'USER-INPUT' and '_Enter':
  • 來自元素與str鍵綁定的事件,該事件將是key+'_Enter',所以應該是這樣的
if thruputEvent == 'USER-INPUT_Enter':

嵌套的 window 或 while 循環使您的代碼復雜,最好使用另一個 function 來處理您的第二個 window,也許像這樣

import PySimpleGUI as sg

def function():

    sg.theme("DarkGrey3")
    layout = [
        [sg.Text()],
        [sg.Input(key='INPUT')],
        [sg.Button('OK'), sg.Button('Cancel')],
        [sg.Text()],
    ]
    window = sg.Window('POPUP', layout, finalize=True, modal=True)
    window['INPUT'].bind("<Return>", "_RETURN")

    while True:

        event, values = window.read()
        if event in (sg.WINDOW_CLOSED, 'Cancel'):
            value = None
            break
        elif event == 'OK':
            value = values['INPUT']
            break

    window.close()
    return value

font = ('Courier New', 11)
sg.theme('DarkBlue3')
sg.set_options(font=font)

layout = [
    [sg.Button("Get Input")],
    [sg.Text("",size=(80, 1), key='TEXT')],
]
window = sg.Window('Title', layout, finalize=True)

while True:

    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'Get Input':
        value = function()
        if value is None:
            window['TEXT'].update('[Cancel]')
        else:
            window['TEXT'].update(value)

window.close()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM