1. 程式人生 > 實用技巧 >Python tkinter之ComboBox(下拉框)

Python tkinter之ComboBox(下拉框)

1、ComboBox的基礎屬性

# -*- encoding=utf-8 -*-
import tkinter
from tkinter import *
from tkinter import ttk

if __name__ == '__main__':
    win = tkinter.Tk()  # 視窗
    win.title('南風丶輕語')  # 標題
    screenwidth = win.winfo_screenwidth()  # 螢幕寬度
    screenheight = win.winfo_screenheight()  # 螢幕高度
    width = 600
    height 
= 500 x = int((screenwidth - width) / 2) y = int((screenheight - height) / 2) win.geometry('{}x{}+{}+{}'.format(width, height, x, y)) # 大小以及位置 value = StringVar() value.set('CCC') values = ['AAA', 'BBB', 'CCC', 'DDD'] combobox = ttk.Combobox( master=win, # 父容器 height=10, #
高度,下拉顯示的條目數量 width=20, # 寬度 state='readonly', # 設定狀態 normal(可選可輸入)、readonly(只可選)、 disabled cursor='arrow', # 滑鼠移動時樣式 arrow, circle, cross, plus... font=('', 20), # 字型 textvariable=value, # 通過StringVar設定可改變的值 values=values, #
設定下拉框的選項 ) print(combobox.keys()) # 可以檢視支援的引數 combobox.pack() win.mainloop()

2、繫結選中事件

# -*- encoding=utf-8 -*-
import tkinter
from tkinter import *
from tkinter import ttk


def choose(event):
    # 選中事件
    print('選中的資料:{}'.format(combobox.get()))
    print('value的值:{}'.format(value.get()))


if __name__ == '__main__':
    win = tkinter.Tk()  # 視窗
    win.title('南風丶輕語')  # 標題
    screenwidth = win.winfo_screenwidth()  # 螢幕寬度
    screenheight = win.winfo_screenheight()  # 螢幕高度
    width = 600
    height = 500
    x = int((screenwidth - width) / 2)
    y = int((screenheight - height) / 2)
    win.geometry('{}x{}+{}+{}'.format(width, height, x, y))  # 大小以及位置
    value = StringVar()
    value.set('CCC')  # 預設選中CCC==combobox.current(2)

    values = ['AAA', 'BBB', 'CCC', 'DDD']
    combobox = ttk.Combobox(
            master=win,  # 父容器
            height=10,  # 高度,下拉顯示的條目數量
            width=20,  # 寬度
            state='normal',  # 設定狀態 normal(可選可輸入)、readonly(只可選)、 disabled
            cursor='arrow',  # 滑鼠移動時樣式 arrow, circle, cross, plus...
            font=('', 20),  # 字型
            textvariable=value,  # 通過StringVar設定可改變的值
            values=values,  # 設定下拉框的選項
            )
    combobox.bind('<<ComboboxSelected>>', choose)
    print(combobox.keys())  # 可以檢視支援的引數
    combobox.pack()
    win.mainloop()