PySampleGUI设计模式 “One-shot Window”

一次性窗口,即不多次读取窗口,窗口被读取后就关闭。

当对窗口(sg.Window)进行读取时,返回一个由event组成的元组 和一个由values组成的字典。

事件(event)是窗口进行读取的原因,事件可以是:点击按钮、点击文本、选择列表项或点击关闭按钮。

值(values)是所有输入元素的字典。字典的键可以自己指定,如没有指定,则会自动提供一个从0开始的整数编号。

下例是一个包含两个输入框的简单界面,单击submit后弹窗显示输出内容。

import PySimpleGUI as sg

layout = [[sg.Text('One-shot window.')],
                 [sg.Text("name"), sg.InputText()],
                 [sg.Text("age"), sg.InputText()],
                 [sg.Submit(), sg.Cancel()]]

window = sg.Window('Window Title', layout)

event, values = window.read()
if event == 'Submit':
    name = values[0]
    age = values[1]
    sg.popup('You entered', name, age)
window.close()

也可以通过手动指定key值,通过key值进行values的筛选。

import PySimpleGUI as sg

layout = [[sg.Text('One-shot window.')],
                 [sg.Text("name"), sg.InputText(key='-NAME-')],
                 [sg.Text("age"), sg.InputText(key='-AGE-')],
                 [sg.Submit(), sg.Cancel()]]

window = sg.Window('Window Title', layout)

event, values = window.read()
if event == 'Submit':
    name = values['-NAME-']
    age = values['-AGE-']
    sg.popup('You entered', name, age)
window.close()