CustomTkinter Combobox选中值写入config.ini失败求助
解决CustomTkinter Combobox值写入config.ini的问题
核心问题拆解
你遇到的两个问题本质是对CustomTkinter Combobox的回调逻辑和StringVar的使用理解有误:
- 打印
choice输出<bound method StringVar.get of ...>:直接引用了StringVar.get方法对象,而非调用该方法获取实际值 - 添加lambda后触发TypeError:Combobox的
command回调默认会传递选中值作为参数,lambda的参数处理不匹配导致报错
错误代码示例(模拟你的场景)
假设你的原始代码类似这样:
import customtkinter as ctk import configparser class CfgFrame(ctk.CTkFrame): def __init__(self, parent): super().__init__(parent) self.create_widgets() def create_widgets(self): self.option_var = ctk.StringVar(value="default") # 错误:直接传递方法对象作为command,或在回调里未调用get() self.combobox = ctk.CTkComboBox(self, variable=self.option_var, command=self.save_config) self.combobox.pack() def save_config(self): # 错误:未调用get()方法,获取到的是方法对象而非值 choice = self.option_var.get print(choice) # 写入配置的代码 config = configparser.ConfigParser() config.read('config.ini') config['Settings']['Option'] = choice with open('config.ini', 'w') as f: config.write(f)
分步解决方案
1. 正确获取StringVar的值
必须调用get()方法才能拿到实际的选中值,而非直接引用方法:
# 错误写法 choice = self.option_var.get # 正确写法 choice = self.option_var.get()
2. 适配Combobox的回调参数
CustomTkinter的CTkComboBox会自动把选中的选项值作为参数传递给command指定的函数,所以回调函数需要适配这个参数:
方案一:直接接收选中值
修改回调函数,让它接收参数,直接使用传递的值:
def create_widgets(self): self.option_var = ctk.StringVar(value="default") # 直接绑定回调函数,自动接收选中值 self.combobox = ctk.CTkComboBox(self, variable=self.option_var, command=self.save_config) self.combobox.pack() def save_config(self, selected_value): # 直接使用传递的选中值,或用self.option_var.get()获取结果一致 print(selected_value) # 处理配置文件读写,先检查section是否存在 config = configparser.ConfigParser() config.read('config.ini') if 'Settings' not in config.sections(): config.add_section('Settings') config.set('Settings', 'Option', selected_value) with open('config.ini', 'w') as config_file: config.write(config_file)
方案二:用lambda传递额外参数
如果需要给回调传递额外参数(比如配置项的键名),要在lambda里接收Combobox自动传递的选中值,再传给回调:
def create_widgets(self): self.option_var = ctk.StringVar(value="default") # lambda接收选中值val,再传给save_config并带上额外参数config_key self.combobox = ctk.CTkComboBox( self, variable=self.option_var, command=lambda val: self.save_config(val, 'Option') ) self.combobox.pack() def save_config(self, selected_value, config_key): config = configparser.ConfigParser() config.read('config.ini') if 'Settings' not in config.sections(): config.add_section('Settings') config.set('Settings', config_key, selected_value) with open('config.ini', 'w') as config_file: config.write(config_file)
3. 恢复Combobox的触发功能
之前错误的回调绑定(比如直接传self.option_var.get)会因为参数不匹配触发报错,导致Combobox后续停止响应。使用上述正确的回调方式后,触发逻辑会恢复正常。
验证效果
假设你的config.ini初始内容为:
[Settings] Option = default
选中Combobox的新选项后,打开config.ini即可看到对应的值已更新。
内容的提问来源于stack exchange,提问作者modded m
相关产品推荐
相关产品推荐

