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

Last updated Dec 31, 2021

In Tkinter, we use the Combobox widgets to create dropdown lists with some values in them. A user can be able to make a single selection from these dropdown lists, and once a selection is made, the value from the dropdown lists automatically gets replaced by the Combobox widget's default value. However, a user may wish to delete the selected text from the Combobox widget. In this post, we are going to explore how a user can be able to clear the text field part of the Combobox widget.

 

How to clear a text field in the Tkinter Combobox widget

You can clear the Tkinter combobox widget text field by setting its value to NULL. To do this, we use the set ("") method. The following code snippet illustrates how this method works in the Tkinter combobox widgets

from tkinter import *

from tkinter import ttk

win = Tk()

win.geometry("500x250")

def clear_cb():

    cb.set('')

n = ('Java', 'Kotlin', 'Python', 'R', 'C#', 'C++', 'PHP')

var = StringVar()

cb = ttk.Combobox(win, textvariable=var)

cb['values'] = n

cb['state'] = 'readonly'

cb.pack(fill='x', padx=5, pady=5)

button = Button(win, text="delete", command=clear_cb)

button.pack()

win.mainloop()

 

Tkinter combobox clear

Output

The above code snippet shows a window with a Combobox widget that enables the user to choose from a list of seven programming languages. There is a "delete" button underneath the Combobox widget that clears the selection made

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

808 Views