无法从ttk.Combobox获取输入,报错AttributeError: 'NoneType' object has no attribute 'get'求助
解决ttk.Combobox调用
get()时的AttributeError问题 我一眼就看出问题所在了——你犯了Tkinter新手常踩的一个小坑!
这个AttributeError: 'NoneType' object has no attribute 'get'错误的根源是:你把Combobox的创建语句和grid()布局方法写在了同一行,而Tkinter的所有几何布局方法(grid()、pack()、place())都会返回None。这就导致你的combobox_sensortype、combobox_dem_dop这些变量根本不是Combobox实例,而是被赋值成了None,调用get()方法自然会报错。
举个直观的对比:
错误写法:
widget = ttk.Widget(...).grid(...)→widget的值是None
正确写法:widget = ttk.Widget(...)然后widget.grid(...)→widget引用的是组件实例
修正后的代码
# 创建comboboxes实例 combobox_sensortype = ttk.Combobox(root, values=('RGB','MS'), state='readonly') # 单独调用grid()布局 combobox_sensortype.grid(row=3,column=2) combobox_dem_dop = ttk.Combobox(root, values=('DEM','DOP'), state='readonly') combobox_dem_dop.grid(row=4,column=2) combobox_sensortype_def = ttk.Combobox(root, values=('RGB_HZ','RGB_MR','MS_HZ','MS_MR'), state='readonly') combobox_sensortype_def.grid(row=5,column=2) combobox_run_SAGA_bat = ttk.Combobox(root, values=('Yes','No'), state='readonly') combobox_run_SAGA_bat.grid(row=6,column=2) # 现在可以正常调用get()获取用户输入了 sensortype = combobox_sensortype.get() demdop = combobox_dem_dop.get() sensortype_def = combobox_sensortype_def.get() run_SAGA_bat = combobox_run_SAGA_bat.get()
小提醒
以后写Tkinter代码时,记得把组件创建和布局分开成两行,这样变量才能正确指向组件实例,后续的方法调用(比如get()、set())才能正常工作。
内容的提问来源于stack exchange,提问作者Tybald
相关产品推荐
相关产品推荐

