如何获取多个tkinter OptionMenu下拉菜单的选中值
问题原因
- 循环内创建的
value_inside变量被重复赋值,最终仅指向最后一个下拉菜单的StringVar对象,导致提交时只能读取到最后一个菜单的选中值 - 预先定义的
Thruster存储列表未被使用,没有把每个下拉菜单对应的StringVar保存下来
修复方案
将每次循环生成的StringVar存入Thruster列表,提交时遍历列表即可读取所有下拉菜单的选中值,修改后的完整代码如下:
# Import the tkinter module import tkinter # Create the default window root = tkinter.Tk() root.title("Thruster types") #root.geometry('700x500') # Create the list of options options_list = 'Tunnel', 'Azimuth', 'Pod', 'Shaft Line', 'Cycloid' #Create an empty list that I will fill with my inputs Thruster=[None]*5 # Create the optionmenu widget and passing # the options_list and value_inside to it. for i in range (0, 5, 1): # Variable to keep track of the option selected in OptionMenu value_inside = tkinter.StringVar(root) # Set the default value of the variable value_inside.set("Thruster"+str(i+1)) # 存储当前下拉框的StringVar到列表 Thruster[i] = value_inside question_menu = tkinter.OptionMenu(root, value_inside, *options_list) question_menu.pack() def print_answers(): # 遍历读取所有下拉框的选中值 for idx, var in enumerate(Thruster): print(f"Thruster{idx+1} 选中值:{var.get()}") return None # Submit button submit_button = tkinter.Button(root, text='Submit', command=print_answers) submit_button.pack() root.mainloop() # 窗口关闭后打印最终所有选择结果 print("所有推进器最终选择结果:") for idx, var in enumerate(Thruster): print(f"Thruster{idx+1}: {var.get()}")
核心修改点
- 循环中新增
Thruster[i] = value_inside,把每个下拉菜单对应的StringVar实例存入列表,保留所有引用不会被覆盖 - 提交函数和窗口关闭后的打印逻辑,改为遍历整个
Thruster列表读取值,可获取全部5个下拉菜单的选中结果
内容的提问来源于stack exchange,提问作者Francesco
相关产品推荐
相关产品推荐

