要求:PySimpleGUI 交互界面的参数输入后保存下来,下次界面打开直接显示之前输入值
思路:输入把数据保存到文件中,打开界面直接读取数据显示
开始的是使用configparser库 ,自己写了一个读取配置文件,保存配置文件的类
后续发现PySimpleGUI 中就有读写参数的类,使用user_settings_filename即可
参考链接
使用 UserSettings
sg.UserSettings(filename=“配置文件.ini”, path=‘.’,use_config_file=True,convert_bools_and_none=True)
其中参数说明如下:
filename 如果不写,则默认生成与代码同名的文件;
path=“.” 表示配置记录文件保存在当前路径下 ,如果不写路径不好找;
use_config_file=True 表示配置文件是ini 文件,如果不写则默认json 格式;
convert_bools_and_none 默认为True. 通常 INI 文件中的所有设置都是字符串。此参数将 ‘True’、‘False’ 和 ‘None’ 转换为 Python 值True, False,None
cfg = sg.UserSettings(filename="配置文件.ini", path='.',use_config_file=True,convert_bools_and_none=True)
#读取参数,使用get 如果获取不到,可以返回默认值
cfg['Section ']['query1']
cfg['Section '].get('query1', '默认值')
#修改参数
cfg['Section']['query1'], "修改后的参数")
cfg['Section'].set('query2', "修改后的参数")
PySimpleGUI界面输入框保存之前的输入值代码如下
import PySimpleGUI as sg
cfg = sg.UserSettings(filename="配置文件.ini", path='.',use_config_file=True)
#窗口排布
layout = [
[sg.Text('条件一', size=(10, 1)), sg.InputText(cfg['Section'].get('query1', ''), key='-strId2-'),
sg.Text('条件二', size=(10, 1)), sg.InputText(cfg['Section'].get('query2', ''), key='-strId2-')],
[sg.Text('配置信息如下', size=(70, 1)), sg.Button('确定', size=(15, 1)), sg.Button('取消', size=(15, 1))],
[sg.Output(size=(120, 10), font=('宋体', 10))]
]
window = sg.Window('Example', layout)
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, '取消'):
break
elif event == '确定':
#设置参数
cfg['Section'].set('query1', values['-strId2-'])
cfg['Section'].set('query2', values['-strId2-'])
print('{0}开始{0}'.format('*' * 20))
print("修改后参数",cfg['Section'])
print('{0}结束{0}'.format('*' * 20))
window.close()