从组合框获取输入不起作用

Getting inputs from comboboxes doesn't work

我做了几个组合框,用户可以在其中选择预定义的设置:

# create comboboxes for settings
combobox_sensortype = ttk.Combobox(root, values=('RGB','MS'), state='readonly').grid(row=3,column=2)
combobox_dem_dop = ttk.Combobox(root, values=('DEM','DOP'), state='readonly').grid(row=4,column=2)
combobox_sensortype_def = ttk.Combobox(root, values=('RGB_HZ','RGB_MR','MS_HZ','MS_MR'), state='readonly').grid(row=5,column=2)
combobox_run_SAGA_bat = ttk.Combobox(root, values=('Yes','No'), state='readonly').grid(row=6,column=2)
   
# getters for extracting user input from comboboxes
sensortype = combobox_sensortype.get()
demdop = combobox_dem_dop.get()
sensortype_def = combobox_sensortype_def.get()
run_SAGA_bat = combobox_run_SAGA_bat.get()

不幸的是,我明白了: AttributeError: 'NoneType' 对象没有属性 'get'

这里有什么问题? 我真的希望有人能帮忙。

这是因为您调用了方法.grid(row=3,column=2)。这不会 return 任何东西,因此变量的值被设置为 None。要获得结果,请将它们放在不同的行中。所以你应该定义组合框,然后将它网格化。

解法:

import tkinter.ttk as ttk
from tkinter import *

root = Tk()

# create comboboxes for settings
combobox_sensortype = ttk.Combobox(root, values=('RGB', 'MS'), state='readonly')  # define the combobox
combobox_sensortype.grid(row=3, column=2)  # grid it!

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)

# getters for extracting user input from comboboxes
sensortype = combobox_sensortype.get()
demdop = combobox_dem_dop.get()
sensortype_def = combobox_sensortype_def.get()
run_SAGA_bat = combobox_run_SAGA_bat.get()


root.mainloop()