如何清除tkinter中的ttk.Combobox文字欄位部分?


Combobox小部件是tkinter中一種百搭小部件,用於建立包含某些值的下拉列表。您可以從下拉列表中選擇一個值,該值將替換為組合框小部件的預設值。您可以透過初始化建構函式Combobox(root, width, text)小部件來建立一個組合框小部件。

考慮這樣一種情況,如果使用者希望清除組合框小部件中選定的值,那麼唯一的方法是使用set (' ')方法將組合框小部件的值設定為NULL。以下示例展示瞭如何執行此操作。

示例

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Create a function to clear the combobox
def clear_cb():
   cb.set('')
   
# Define Days Tuple
days= ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')

# Create a combobox widget
var= StringVar()
cb= ttk.Combobox(win, textvariable= var)
cb['values']= days
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)

# Create a button to clear the selected combobox text value
button = Button(win, text= "Clear", command= clear_cb)
button.pack()

win.mainloop()

輸出

執行以上程式碼將顯示一個帶有組合框小部件的視窗和一個按鈕“清除”以清除組合框小部件中選定的值。

現在點選“清除”按鈕以清除組合框小部件中選定的值。

更新於:16-12-2021

4K+瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.