Python之tkinter組合框Combobox用法及說明
組合框 Combobox 簡介
Combobox 可以翻譯為組合框,這是tkinter.ttk
的 Widget控件,它的特性與OptionMenu類似,可以說它是Entry和下拉菜單的組合,構造方法如下
Combobox(父對象, options)
參數(shù):
- 第一個參數(shù):子組件,表示這個組合框?qū)⒔⒃谀囊粋€窗口內(nèi)
- 第二個參數(shù):
options
,參數(shù)如下
參數(shù) | 含義 |
---|---|
textvariable | 可以設置Combobox 的變量值 |
value | Combobox 的選項內(nèi)容以元組方式存在 |
建立 Combobox
在 Combobox()的構造方法中,可以使用Value 參數(shù)建立選項內(nèi)容
例子:
import tkinter import tkinter.ttk root = tkinter.Tk() var = tkinter.StringVar() combobox = tkinter.ttk.Combobox(root, textvariable=var, value=('python', 'java', 'C', 'C++')) combobox.pack(padx=5, pady=10) root.mainloop()
運行結果:
若是選項很多,可以使用獨立在Combobox()外來處理
例子:
combobox = tkinter.ttk.Combobox(root, textvariable=var) combobox['value'] = ('python', 'java', 'C', 'C++')
運行結果與上面相同
設置默認選項 current()
例子:
import tkinter import tkinter.ttk root = tkinter.Tk() var = tkinter.StringVar() combobox = tkinter.ttk.Combobox(root, textvariable=var) combobox['value'] = ('python', 'java', 'C', 'C++') combobox.current(0) combobox.pack(padx=5, pady=10) root.mainloop()
運行結果:
或者可以使用var.set()
方法來設置,但是相比而言還是current()
比較便利
例子:
var.set(combobox['value'][0]) # combobox.current(0)
運行結果一樣
獲得目前選項 get()
例子:
import tkinter import tkinter.ttk def show(): # 使用var.get()來獲得目前選項內(nèi)容 varLabel.set(var.get()) root = tkinter.Tk() var = tkinter.StringVar() combobox = tkinter.ttk.Combobox(root, textvariable=var) combobox['value'] = ('python', 'java', 'C', 'C++') combobox.current(0) combobox.pack(padx=5, pady=10) varLabel = tkinter.StringVar() label = tkinter.Label(root, textvariable=varLabel, width=20, height=3, bg='lightblue', fg='red') label.pack() button = tkinter.Button(root, text='print', command=show) button.pack() root.mainloop()
運行結果:
綁定 Combobox
當Combobox 中的選項有變動時,會產(chǎn)生虛擬事件<<ComboboxSelected>>
,可以使用這個特性將此事件綁定處理方法
例子:
import tkinter import tkinter.ttk def show(event): # 使用var.get()來獲得目前選項內(nèi)容 varLabel.set(var.get()) root = tkinter.Tk() var = tkinter.StringVar() combobox = tkinter.ttk.Combobox(root, textvariable=var) combobox['value'] = ('python', 'java', 'C', 'C++') combobox.current(0) combobox.bind('<<ComboboxSelected>>', show) combobox.pack(side=tkinter.LEFT, padx=5, pady=10) varLabel = tkinter.StringVar() label = tkinter.Label(root, textvariable=varLabel, width=6, bg='lightblue', fg='red') label.pack(side=tkinter.LEFT) root.mainloop()
運行結果:
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Anaconda 查看、創(chuàng)建、管理和使用python環(huán)境的方法
這篇文章主要介紹了Anaconda 查看、創(chuàng)建、管理和使用python環(huán)境的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12python神經(jīng)網(wǎng)絡Keras搭建RFBnet目標檢測平臺
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡Keras搭建RFBnet目標檢測平臺,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05