在本文中,将介绍如何创建一个 tkinter Combobox 组合框小部件,该小部件允许用户从一组值中选择一个值。
Combobox 组合框小部件是新增的 Ttk 主题小部件,是 Entry 文本框和 Listbox 列表框的组合。除了允许在一组值中选择一个值外,它还允许输入自定义值。
创建组合框要创建组合框小部件,使用以下构造函数。
current_var = tk.StringVar()combobox = ttk.Combobox(master, textvariable=current_var)获取组合框选定的值textvariable 参数将变量链接到 current_var。要获取当前组合框选定的值,可以使用 current_var 变量。
current_value = current_var.get()或者,直接使用 combobox 对象的 get() 方法:
current_value = combobox.get()设置组合框的值要设置当前值,可以使用 current_var 变量或 combobox 对象的 set() 方法。
current_value.set(new_value)combobox.set(new_value)默认情况下,可以直接在组合框中输入值。如果不允许直接输入值,可以将组合框设置为只读 readonly 否则,设置为 normal。
combobox['state'] = 'readonly'批量设置组合框的值可以为组合框分配一个列表或元组,进行批量赋值。
combobox['values'] = ('value1', 'value2', 'value3')`绑定事件当组合框的值发生更改时,可以触发事件,使用 bind() 方法绑定 <<ComboboxSelected>> 事件。
combobox.bind('<<ComboboxSelected>>', callback)
Combobox 组合框示例
import tkinter as tkfrom tkinter.messagebox import showinfofrom tkinter import ttkfrom calendar import month_namefrom datetime import datetimeroot = tk.Tk()root.geometry('600x400+200+200')root.title('Combobox 组合框演示')def year_changed(event): showinfo(title='结果', message=f'你选择了 {selected_year.get()}!' )def month_changed(event): showinfo(title='结果', message=f'你选择了 {selected_month.get()}!' )label = tk.Label(text="请选择年份:")label.pack(fill=tk.X, padx=5, pady=5)selected_year = tk.StringVar()combobox1 = ttk.Combobox(root, textvariable=selected_year)combobox1['values'] = [2023, 2024, 2025]combobox1['state'] = 'readonly'combobox1.pack(padx=5, pady=5)combobox1.bind('<<ComboboxSelected>>', year_changed)label = tk.Label(text="请选择月份:")label.pack(fill=tk.X, padx=5, pady=5)selected_month = tk.StringVar()combobox2 = ttk.Combobox(root, textvariable=selected_month)combobox2['values'] = [month_name[m][0:3] for m in range(1, 13)]combobox2['state'] = 'readonly'combobox2.pack(padx=5, pady=5)combobox2.bind('<<ComboboxSelected>>', month_changed)# 设置当前月份为组合框的当前值current_month = datetime.now().strftime('%b')combobox2.set(current_month)root.mainloop()

