How to clear the text field part of ttk.Combobox in tkinter?


The Combobox widget is one of the versatile widgets in tkinter that is used to create a dropdown list containing some values in it. You can select a value from the dropdown list that gets replaced by the default value of the combobox widget. You can create a combobox widget by initializing the constructor of Combobox(root, width, text) widget.

Consider the case, if the user wants to clear the selected value from the combobox widget, the only way you can do so is to set the value of the combobox widget as NULL by using the set (' ') method. The following example demonstrates how to do it.

Example

# 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()

Output

Running the above code will display a window with a combobox widget and a button "Clear" to clear the selected value from the combobox widget.

Now click on the "Clear" button to clear the selected value from the combobox widget.

Updated on: 16-Dec-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements