PySimpleGUI新手求助:按钮文本清空及Excel列异常问题
问题排查与解决方案
针对你遇到的两个问题,逐一分析并给出修复方案:
问题1:点击Submit/Clear后日历按钮文本被清空
原因:PySimpleGUI中,未显式指定key的控件会默认使用其显示文本作为key。你的CalendarButton没有设置key,所以values字典里会包含"Job Start"和"Job Stop"这两个键。执行clear_input时,window[key]('')会把这两个按钮的文本清空。
修复方案:给两个CalendarButton添加独立的key(采用PySimpleGUI惯例的全大写加连字符命名风格),避免和输入框key冲突,也防止误清空按钮文本:
[sg.CalendarButton("Job Start", key='-CAL_START-', close_when_date_chosen=True, target="Clock In", location=(20,20), no_titlebar=False), sg.Input(key='Clock In', size=(15,1))], [sg.CalendarButton("Job Stop", key='-CAL_STOP-', close_when_date_chosen=True, target="Clock Out", location=(20,20),no_titlebar=False), sg.Input(key='Clock Out', size=(15,1))],
问题2:Excel文件多生成「Job Start」「Job Stop」列
原因:values字典里包含了日历按钮的默认key,创建new_record时会把这些键作为列加入DataFrame,最终导出到Excel。
修复方案:创建DataFrame时,只保留需要的输入字段key,过滤掉控件相关的key。可以定义字段列表,从values中提取对应数据:
# 在Submit事件处理中修改 if event == 'Submit': # 定义需要保存的字段列表 fields = ['Work Order No.', 'Part No.', 'Employee No.', 'Clock In', 'Clock Out'] # 从values中提取指定字段的数据 filtered_values = {k: values[k] for k in fields} new_record = pd.DataFrame(filtered_values, index=[0]) df = pd.concat([df, new_record], ignore_index=True) df.to_excel(EXCEL_FILE, index=False) sg.popup('Data saved!') clear_input()
同时可以优化clear_input函数,只清空输入框的key,避免误操作其他控件:
def clear_input(): input_keys = ['Work Order No.', 'Part No.', 'Employee No.', 'Clock In', 'Clock Out'] for key in input_keys: window[key]('') return None
完整修复后的代码
from pathlib import Path import PySimpleGUI as sg from datetime import datetime import pandas as pd import time # Add some color to the window sg.theme('DarkTeal9') current_dir = Path(__file__).parent if '__file__' in locals() else Path.cwd() EXCEL_FILE = current_dir / 'ClockInOut.xlsx' # Load the data if the file exists, if not, create a new DataFrame with columns if EXCEL_FILE.exists(): df = pd.read_excel(EXCEL_FILE) else: df = pd.DataFrame(columns=['Work Order No.', 'Part No.', 'Employee No.', 'Clock In', 'Clock Out']) layout = [ [sg.Text('Please fill out the following fields:')], [sg.Text('Work Order No.', size=(15,1)), sg.InputText(key='Work Order No.')], [sg.Text('Part No.', size=(15,1)), sg.InputText(key='Part No.')], [sg.Text('Employee No.', size=(15,1)), sg.InputText(key='Employee No.')], [sg.CalendarButton("Job Start", key='-CAL_START-', close_when_date_chosen=True, target="Clock In", location=(20,20), no_titlebar=False), sg.Input(key='Clock In', size=(15,1))], [sg.CalendarButton("Job Stop", key='-CAL_STOP-', close_when_date_chosen=True, target="Clock Out", location=(20,20),no_titlebar=False), sg.Input(key='Clock Out', size=(15,1))], [sg.Submit(), sg.Button('Clear'), sg.Exit()] ] window = sg.Window('Simple data entry form', layout) def clear_input(): input_keys = ['Work Order No.', 'Part No.', 'Employee No.', 'Clock In', 'Clock Out'] for key in input_keys: window[key]('') return None while True: event, values = window.read() if event == sg.WIN_CLOSED or event == 'Exit': break if event == 'Clear': clear_input() if event == 'Submit': fields = ['Work Order No.', 'Part No.', 'Employee No.', 'Clock In', 'Clock Out'] filtered_values = {k: values[k] for k in fields} new_record = pd.DataFrame(filtered_values, index=[0]) df = pd.concat([df, new_record], ignore_index=True) df.to_excel(EXCEL_FILE, index=False) # This will create the file if it doesn't exist sg.popup('Data saved!') clear_input() window.close()
内容的提问来源于stack exchange,提问作者theoneandonlyjonasv
相关产品推荐
相关产品推荐

