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

如何使用Python获取下拉菜单信息并添加至数组?

获取Tkinter OptionMenu选中值的方法

嘿,别担心,这个问题其实超容易解决!你已经做对了最关键的一步——用StringVar和OptionMenu绑定了,要获取选中的选项,直接用这个variable的.get()方法就可以,和你处理输入框的逻辑完全一致~

你看,你定义的variable = StringVar(fp_frame)已经和OptionMenu关联起来了,当用户选择下拉菜单里的选项时,这个变量会自动更新为选中的内容。所以在你需要获取数据的地方(比如点击提交按钮的时候),只需要调用:

selected_option = variable.get()

然后就可以把这个selected_option存入你的数组里了。我给你补个完整的示例,方便你理解:

from tkinter import Tk, Frame, StringVar, OptionMenu, Button

# 用来存储数据的数组
your_data_array = []

def save_selected_option():
    # 获取下拉菜单选中的值
    selected_question = variable.get()
    # 存入数组
    your_data_array.append(selected_question)
    print(f"已保存问题:{selected_question}")
    print(f"当前数组内容:{your_data_array}")

root = Tk()
fp_frame = Frame(root)
fp_frame.pack(padx=20, pady=20)

OPTIONS = [
    "What was my first pet's name?",
    "What was your favorite food as a child?",
    "What was the make of your first car?",
    "What is your mother's maiden name?"
]

variable = StringVar(fp_frame)
variable.set(OPTIONS[0]) # 设置默认值

w = OptionMenu(fp_frame, variable, *OPTIONS)
w.place(x=60, y=25, width = 240, height = 28)

# 添加一个按钮来触发保存操作
submit_btn = Button(fp_frame, text="保存选项", command=save_selected_option)
submit_btn.place(x=60, y=65)

root.mainloop()

核心逻辑就是:和OptionMenu绑定的StringVar会实时同步选中状态,调用它的.get()就能拿到当前选中的选项值,和你处理输入框的方式一模一样,是不是很简单?

内容的提问来源于stack exchange,提问作者Pearce Maguire

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:20:29