【问题标题】:Interactive popup window in pysimpleguipysimplegui 中的交互式弹出窗口
【发布时间】:2021-09-24 18:49:40
【问题描述】:

我创建了一个如下所示的预测用户界面

代码如下:

items = [
    "Automobile", "Chemical", "Engineering/Consulting", "FMCG",
    "Healthcare/Hospitality", "Infrastructue", "IT/Comm/DC", "Manufacturing",
    "Mines", "Energy/Oil & Gas", "Pharma", "Retail", "Cement",
]
length = len(items)
size = (max(map(len, items)), 1)

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

column_layout = []
line = []
num = 4
for i, item in enumerate(items):
    line.append(sg.Button(item, size=size, metadata=False))
    if i%num == num-1 or i==length-1:
        column_layout.append(line)
        line = []

layout = [
    [sg.Text('Choose the Industry')],
    [sg.Column(column_layout)],
    [sg.Text(size=(50,1),key=('loaded'))],
    [sg.Text('Enter Observation/Recommendation: ', size =(26, 1)), sg.InputText(do_not_clear=False)],
    [sg.Button("Predict Risk", bind_return_key=True,metadata=False)],
    [sg.Text(size=(30,1),key=('output'))],
    [sg.Text('If the above prediction is correct select \'yes\' else select the correct risk.')],
    [sg.Button("Yes"),sg.Button("Low"),sg.Button("Medium")],
    [sg.Text(size=(30,2),key=('trained'))],
    [sg.Button("Exit"),sg.Button("Clear Fields")]
]

window=sg.Window("Risk Predictor", layout, use_default_focus=False, finalize=True)
for key in window.key_dict:    # Remove dash box of all Buttons
    element = window[key]
    if isinstance(element, sg.Button):
        element.block_focus()

#window=sg.Window("Risk Predictor",layout)

while True:
    event, values = window.read()
    # End program if user closes window or
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == "Mines":
        window['Mines'].metadata = True
        
        df=pd.read_csv('./Audit data_Observation & Risk.csv')
        #df1=balancing(df)
        df1=df
        window['loaded'].update("Mines data is loaded.")
        obs=values[0]
        #if obs!="":
    if event == "Predict Risk" and window["Mines"].metadata and values[0]!="":
        with open("./sgd.pickle", 'rb') as f:
            sgd = pickle.load(f)
        window['trained'].update("")
        output=output_sample(df1,sgd,values[0])
        output1="The Risk prediction is "+output
        window['output'].update(output1)
        window['Predict Risk'].metadata=True
    if event == 'Yes' and window['Predict Risk'].metadata==True:
        newy=preprocess_text(output)
        retrain(df1,values[0],newy)
        window['trained'].update("The model has been trained on new data.")
        continue
    elif event =='Low' and window['Predict Risk'].metadata==True:
        newy="Low"
        retrain(df1,values[0],newy)
        window['trained'].update("The model has been trained on updated data.")
        continue
    elif event =='Medium' and window['Predict Risk'].metadata==True:
        newy="Medium"
        retrain(df1,values[0],newy)
        window['trained'].update("The model has been trained on updated data.")
        continue
    if event=='Clear Fields':
        window['loaded'].update("")
        window['output'].update("")
        window['trained'].update("")
        values[0]=''
        window[event].metadata=False
        window['Predict Risk'].metadata=False
window.close()

无论如何它还没有完成。我想把这个 UI 分成三个部分。

  1. 当应用程序运行时,只有Choose the industry 部分出现。
  2. 选择行业后,弹出窗口会打开Enter the ObservationPredict Risk
  3. 当点击Predict Risk 时,另一个弹出窗口显示预测和反馈机制。

所以我的问题是如何制作交互式弹出窗口?

【问题讨论】:

    标签: python pysimplegui


    【解决方案1】:

    只需在您的函数中创建一个带有modal=True 的新窗口,并传递参数并返回您需要的值。选项modal=True 如果为True,则此窗口将是用户在关闭之前唯一可以与之交互的窗口。

    前一个窗口的设置modal=True 将被删除,所以最好只对同时存在的两个窗口。当然,更多的窗口也可以工作,但需要更多的设置。

    这里是演示代码,

    import PySimpleGUI as sg
    
    def block_focus(window):
        for key in window.key_dict:    # Remove dash box of all Buttons
            element = window[key]
            if isinstance(element, sg.Button):
                element.block_focus()
    
    def popup_predict_risk(industry):
    
        col_layout = [[sg.Button("Predict Risk", bind_return_key=True), sg.Button('Cancel')]]
        layout = [
            [sg.Text(f"Industry: {industry}")],
            [sg.Text('Enter Observation/Recommendation: '), sg.InputText(key='Observation')],
            [sg.Column(col_layout, expand_x=True, element_justification='right')],
        ]
        window = sg.Window("Predict Risk", layout, use_default_focus=False, finalize=True, modal=True)
        block_focus(window)
        event, values = window.read()
        window.close()
        return values['Observation'] if event == 'Predict Risk' else None
    
    def popup_prediction(industry, observation):
    
        col_layout = [[sg.Button('OK')]]
        layout = [
            [sg.Text("Here's the result\n")],
            [sg.Text(f"industry   : {industry}")],
            [sg.Text(f"Observation: {observation}")],
            [sg.Column(col_layout, expand_x=True, element_justification='right')],
        ]
        window = sg.Window("Prediction", layout, use_default_focus=False, finalize=True, modal=True)
        block_focus(window)
        event, values = window.read()
        window.close()
        return None
    
    items = [
        "Automobile", "Chemical", "Engineering/Consulting", "FMCG",
        "Healthcare/Hospitality", "Infrastructue", "IT/Comm/DC", "Manufacturing",
        "Mines", "Energy/Oil & Gas", "Pharma", "Retail", "Cement",
    ]
    length = len(items)
    size = (max(map(len, items)), 1)
    
    sg.theme("DarkBlue3")
    sg.set_options(font=("Courier New", 11))
    
    column_layout = []
    line = []
    num = 4
    for i, item in enumerate(items):
        line.append(sg.Button(item, size=size, metadata=False))
        if i%num == num-1 or i==length-1:
            column_layout.append(line)
            line = []
    
    layout = [
        [sg.Text('Choose the Industry')],
        [sg.Column(column_layout)],
    ]
    window=sg.Window("Risk Predictor", layout, use_default_focus=False, finalize=True)
    block_focus(window)
    
    sg.theme("DarkGreen3")
    while True:
    
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event in items:
            industry = event
            observation = popup_predict_risk(industry)
            if observation is not None:
                popup_prediction(industry, observation)
    
    window.close()
    

    【讨论】:

    • 谢谢。它按预期工作。就2个问题。 1.modal=True是做什么的? 2.element.block_focus()是做什么的?我知道我用过第二个,但不知道它的作用。
    • Option modal=True if True 那么这个窗口将是用户可以交互的唯一窗口,直到它被关闭。 element.block_focus()通过键盘禁用元素获取焦点,sg.Window中的use_default_focus=False选项,Windows系统中sg.Button上不会出现黑色虚线框。
    猜你喜欢
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2018-03-30
    • 2021-11-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多