combobox控件,下拉菜单控件
combobox控件在tkinter中的ttk下
简单的实现下:
1 import tkinter 2 from tkinter import ttk # 导入ttk模块,因为下拉菜单控件在ttk中 3 4 wuya = tkinter.Tk() 5 wuya.title("wuya") 6 wuya.geometry("300x200+10+20") 7 8 # 创建下拉菜单 9 cmb = ttk.Combobox(wuya) 10 cmb.pack() 11 12 13 wuya.mainloop()
结果:
给下拉菜单中添加内容:
1 import tkinter 2 from tkinter import ttk # 导入ttk模块,因为下拉菜单控件在ttk中 3 4 wuya = tkinter.Tk() 5 wuya.title("wuya") 6 wuya.geometry("300x200+10+20") 7 8 9 # 创建下拉菜单 10 cmb = ttk.Combobox(wuya) 11 cmb.pack() 12 # 设置下拉菜单中的值 13 cmb['value'] = ('上海','北京','天津','广州') 14 15 # 设置默认值,即默认下拉框中的内容 16 cmb.current(2) 17 # 默认值中的内容为索引,从0开始 18 19 wuya.mainloop()
结果:
绑定事件:
1 import tkinter 2 from tkinter import ttk # 导入ttk模块,因为下拉菜单控件在ttk中 3 4 wuya = tkinter.Tk() 5 wuya.title("wuya") 6 wuya.geometry("300x200+10+20") 7 8 9 # 创建下拉菜单 10 cmb = ttk.Combobox(wuya) 11 cmb.pack() 12 # 设置下拉菜单中的值 13 cmb['value'] = ('上海','北京','天津','广州') 14 15 # 设置默认值,即默认下拉框中的内容 16 cmb.current(2) 17 # 默认值中的内容为索引,从0开始 18 19 # 执行函数 20 def func(event): 21 text.insert('insert',cmb.get()+" ") 22 cmb.bind("<<ComboboxSelected>>",func) 23 24 text = tkinter.Text(wuya) 25 text.pack() 26 27 wuya.mainloop()
结果: