Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การตั้งค่า Default Value ให้ ttk.Combobox ใน Tkinter

Tkinter ttk.Combobox เป็น Dropdown list ผสม Entry สามารถตั้งค่าเริ่มต้นได้ด้วยเมธอด current(index) โดย index เริ่มจาก 0

ขั้นตอนการทำงาน

  1. นำเข้า tkinter และ ttk
  2. สร้าง Combobox: ttk.Combobox(win, state="readonly")
  3. กำหนดค่าที่เลือกได้: combobox['values'] = ('C++', 'Java', 'Python')
  4. ตั้งค่าเริ่มต้น: combobox.current(2) (index 2 = 'Python')
  5. จัด Layout และรัน

ตัวอย่างโค้ด


from tkinter import *
from tkinter import ttk

win = Tk()
win.geometry("750x250")

combobox = ttk.Combobox(win, state="readonly")
combobox['values'] = ('C++', 'Java', 'Python')
combobox.current(2)  # index 2 = 'Python'
combobox.pack(pady=30, ipadx=20)

win.mainloop()

สถานะ (state) ของ Combobox

  • 'normal' - พิมพ์ได้ เลือกได้ (ค่าเริ่มต้น)
  • 'readonly' - เลือกได้อย่างเดียว ไม่พิมพ์ (แนะนำ)
  • 'disabled' - ใช้งานไม่ได้

การอ่านค่าที่เลือก


def on_select(event):
    print("Selected:", combobox.get())
    print("Index:", combobox.current())

combobox.bind('<>', on_select)

# หรืออ่านโดยตรง
value = combobox.get()
index = combobox.current()

การตั้งค่าเริ่มต้นแบบไม่ใช้ current()


# ใช้ StringVar
var = StringVar(value="Python")
combobox = ttk.Combobox(win, textvariable=var, values=('C++', 'Java', 'Python'))
# ค่าเริ่มต้นจะเป็น "Python" อัตโนมัติ

การปรับแต่งเพิ่มเติม


# ความสูง Dropdown list
combobox.configure(height=10)  # แสดง 10 รายการ

# ฟอนต์
combobox.configure(font=('Helvetica', 12))

# Post command - เรียกก่อนเปิด dropdown
def update_values():
    combobox['values'] = get_dynamic_options()
combobox.configure(postcommand=update_values)

การประยุกต์ใช้

เหมาะสำหรับ: เลือกหมวดหมู่ (Category), เลือกประเทศ/ภาษา, เลือกการตั้งค่า (Settings), Form input ที่มีตัวเลือกจำกัด