在PySimpleGUI中,可以通过单击按钮来添加字段或元素。具体实现的步骤如下:
import PySimpleGUI as sg
sg.Window()
函数创建一个GUI窗口,可以设置窗口的标题、布局等属性。例如:window = sg.Window('Add Field Example', layout)
sg.Text()
、sg.Input()
等函数创建文本、输入框等元素。例如:layout = [
[sg.Text('Field Name:'), sg.Input(key='-FIELD-')],
[sg.Button('Add Field', key='-ADD-')],
[sg.Text('Fields:', size=(20, 1))],
[sg.Listbox(values=[], size=(30, 5), key='-FIELDS-')]
]
window.read()
函数读取窗口中的事件和值,并根据事件类型进行相应的处理。例如,当点击"Add Field"按钮时,可以通过事件处理函数来添加字段或元素。代码示例如下:while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == '-ADD-':
field_name = values['-FIELD-']
window['-FIELDS-'].update(values['-FIELDS-'] + [field_name])
window['-FIELDS-'].update()
方法来更新窗口中的字段或元素。例如,将新添加的字段名添加到列表框中。代码示例如下:window['-FIELDS-'].update(values['-FIELDS-'] + [field_name])
sg.WINDOW_CLOSED
来关闭窗口。例如:if event == sg.WINDOW_CLOSED:
break
完整的示例代码如下:
import PySimpleGUI as sg
layout = [
[sg.Text('Field Name:'), sg.Input(key='-FIELD-')],
[sg.Button('Add Field', key='-ADD-')],
[sg.Text('Fields:', size=(20, 1))],
[sg.Listbox(values=[], size=(30, 5), key='-FIELDS-')]
]
window = sg.Window('Add Field Example', layout)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == '-ADD-':
field_name = values['-FIELD-']
window['-FIELDS-'].update(values['-FIELDS-'] + [field_name])
window.close()
这样,当点击"Add Field"按钮时,输入框中的字段名将会添加到列表框中。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云