You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取多个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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:18:04