PySimpleGUI更换显示图片及表单上传后仅展示已填字段的技术问询
需求实现方案
问题1:点击图片按钮更换图片并随表单保存
完全可以实现,具体修改如下:
代码修改部分
首先在初始定义中新增变量存储当前图片的Base64:
flower_base64 = "image code here" current_img_base64 = flower_base64 # 存储当前显示图片的base64编码
然后在事件循环中添加图片按钮的点击处理逻辑:
if event == '-GRAPH-': # 弹出文件选择器,限制仅选择常见图片格式 img_path = sg.popup_get_file("选择图片", file_types=(("图片文件", "*.png;*.jpg;*.jpeg"),), no_window=True) if img_path: # 读取图片文件并转换为base64编码 with open(img_path, "rb") as f: current_img_base64 = base64.b64encode(f.read()).decode() # 更新按钮显示的图片 window['-GRAPH-'].update(image_data=current_img_base64)
修改Save和Load事件,让图片数据随表单状态一起保存/恢复:
if event == 'Save': filename = sg.popup_get_file("Save", save_as=True, no_window=True, default_extension=".pkl") if filename: # 获取窗口元素状态并返回状态字典 window_state = window.SaveToDisk(filename, return_state=True) # 将当前图片的base64数据加入状态字典 window_state['current_img'] = current_img_base64 # 重新保存包含图片的完整状态 import pickle with open(filename, 'wb') as f: pickle.dump(window_state, f) if event == 'Load': filename = sg.popup_get_file('Load', no_window=True) if filename: import pickle with open(filename, 'rb') as f: window_state = pickle.load(f) # 加载窗口原有表单状态 window.LoadFromDisk(filename, state=window_state) # 恢复图片显示 current_img_base64 = window_state.get('current_img', flower_base64) window['-GRAPH-'].update(image_data=current_img_base64)
问题2:加载表单后仅展示已填写的字段
可以实现,核心是加载时检查每个输入框的内容是否非空,仅显示对应有内容的字段布局,同时修正原代码中错误的判断逻辑(原代码if "-IT2-"是恒成立的,必须判断输入框的实际值)。
代码修改部分
在Load事件中,替换原有的布局显示判断逻辑为:
# 定义输入框与对应布局的映射关系,方便后续扩展字段 field_layout_map = { "-IT2-": ("-LAY2-", "-LAYA-"), # 输入框key: (要显示的布局key, 要隐藏的布局key) "-IT3-": ("-LAY3-", "-LAYB-") } # 遍历检查每个输入框,控制对应布局的显示/隐藏 for input_key, (show_layout, hide_layout) in field_layout_map.items(): if values[input_key].strip(): window[show_layout].update(visible=True) window[hide_layout].update(visible=False) else: window[show_layout].update(visible=False) window[hide_layout].update(visible=True)
完整Load事件代码
if event == 'Load': filename = sg.popup_get_file('Load', no_window=True) if filename: import pickle with open(filename, 'rb') as f: window_state = pickle.load(f) # 加载窗口原有表单状态 window.LoadFromDisk(filename, state=window_state) # 恢复图片显示 current_img_base64 = window_state.get('current_img', flower_base64) window['-GRAPH-'].update(image_data=current_img_base64) # 处理已填写字段的布局显示 field_layout_map = { "-IT2-": ("-LAY2-", "-LAYA-"), "-IT3-": ("-LAY3-", "-LAYB-") } for input_key, (show_layout, hide_layout) in field_layout_map.items(): if values[input_key].strip(): window[show_layout].update(visible=True) window[hide_layout].update(visible=False) else: window[show_layout].update(visible=False) window[hide_layout].update(visible=True)
内容的提问来源于stack exchange,提问作者giovanni trivieri
相关产品推荐
相关产品推荐

