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

如何获取Python Tkinter中Combobox组件的选中返回值

如何获取Tkinter代码中Combobox组件选中项的返回值?

你提供的原始代码片段如下:

combobox_label = tk.Label(top_level, text="How many marks?", font=('Helvetica', 12, 'bold'))

combobox= ttk.Combobox(top_level)

combobox['values'] = [int(i) for i in range(0, marks+1)]

combobox_label.pack()

combobox.pack()

ttk.Combobox 可以直接通过内置的get()方法获取当前选中项的内容,根据使用场景分两种常见用法:

  • 主动触发获取:比如点击确认按钮时读取选中值
    只需要在触发的回调函数里调用combobox.get()即可,注意返回值默认是字符串类型,需要整数的话手动转int,同时要处理未选择时的空值情况,参考代码:
    def get_combobox_value():
        selected = combobox.get()
        if not selected:
            print("未选择任何选项")
            return
        selected_mark = int(selected)
        print(f"选中的分数为:{selected_mark}")
    
    # 绑定到按钮点击事件
    confirm_btn = ttk.Button(top_level, text="确认", command=get_combobox_value)
    confirm_btn.pack()
    
  • 选中时自动获取:用户选择下拉选项后立刻读取值
    给Combobox绑定<<ComboboxSelected>>虚拟事件即可,选项变化时会自动执行绑定的回调:
    def handle_select(event):
        selected = combobox.get()
        if selected:
            print(f"当前选中:{int(selected)}")
    
    combobox.bind("<<ComboboxSelected>>", handle_select)
    

注意事项:

  • 不要尝试用Listbox组件的curselection()方法获取Combobox选中项,ttk.Combobox不支持该方法,get()是官方推荐的取值方式
  • 因为Combobox自带可输入的文本框,get()同时也能读取用户手动在框内输入的内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.22 16:15:00