Tkinter开发:从txt文件动态更新Combobox下拉选项值问题求解
问题修复方案
核心问题点
ValueSource函数没有返回排序后的列表,调用后拿到的是默认的None,自然无法更新Combobox选项Add函数存在缩进错误,且with上下文管理会自动关闭文件,不需要手动调用close- 读取文件内容时未去除每行末尾的换行符,也未过滤空行,会导致选项出现多余空值或者格式异常
- 缺少文件不存在的异常兼容,首次运行无txt文件时会触发报错
修复后完整代码
功能函数部分
def Add(): # 先去除输入首尾空白,过滤空输入 val1 = str(SubKey1.get()).strip() val2 = str(Subkey2.get()).strip() if val1 and val2: with open('ComboValues.txt', 'a+', encoding='utf-8') as file: file.write(f'{val1}\n{val2}\n') def ValueSource(): try: with open('ComboValues.txt', 'r', encoding='utf-8') as inFile: # 去除每行换行符、过滤空行后排序 combobox_value = sorted([line.strip() for line in inFile if line.strip()]) return combobox_value # 兼容首次运行文件不存在的场景 except FileNotFoundError: open('ComboValues.txt', 'w', encoding='utf-8').close() return [] def GetUpdatedValues(): # 正确接收ValueSource返回的排序后列表 values = ValueSource() Root.Combobox['values'] = values
界面代码部分(原有逻辑无明显问题可保留)
class GUI (): def __init__(self, master): self.master = master master.EntryMainKey = Entry(Root, textvariable= MainKey).grid(row=0, columnspan=2) master.EntrySubKey1 = Entry(Root, textvariable= SubKey1).grid(row=1, columnspan=2) master.EntrySubKey2 = Entry(Root, textvariable= Subkey2).grid(row=2, columnspan=2) master.AddButton = Button(Root, text='Add', command=Add).grid(row=3, column=0) master.Combobox = Combobox(Root, state='normal', postcommand=GetUpdatedValues) master.Combobox.grid(row=4, columnspan=2) def main(): GUI(Root) ValueSource() Root.mainloop()
额外优化建议
- 尽量避免使用全局变量
Root、SubKey1、Subkey2,可以把三个功能函数都放到GUI类内部作为方法,通过self访问组件实例和变量,逻辑更清晰也不容易出错 - 写入文件前可以增加去重判断,避免Combobox出现重复选项
- 如果需要支持中文输入,务必给文件操作指定
encoding='utf-8'参数避免乱码
内容的提问来源于stack exchange,提问作者Sheik-Yabouti
相关产品推荐
相关产品推荐

