Search code examples
pythontkintercomboboxttkbootstrap

How to reset a group of comboboxes back to no selection tkinter?


I'm using ttkbootstrap with tkinter and I have 15 ttkbootstrap comboboxes that I want to reset to no selection if a button is pressed. I tried this code I found somewhere, but it does nothing. I did verify I'm hitting the function with a print statement though:

import tkinter
from tkinterr import *
import ttkbootstrap as ttk

def clear():
    print("In the clear function!)
    if isinstance(Widget, ttk.combobox):
    Widget.delete(0,end)

I'm assuming Widget isn't defined properly and that is the issue? I tried using Combobox and ComboBoxWidget, then tried to name a widget instance ,but nothing seems to work.

I put all of the comboboxes in a class so I can pass self to other methods.

The button code is:
    self.clear_button = ttk.Button(button_frame),
    command = lambda: clear(),
etc...

I know I can reset an individual combobox using:

 def clear_combo():
        combobox.delete(0, "end")

I can loop through each combobox by unique name, but I was looking to find a better solution as that seemed clunky. Is there a way to generically select a specific type of ttk widget for this?


Solution

  • If you can put all of the comboboxes in a frame, then you can ask the frame to give you all of its child widgets and you can iterate over them all in a loop.

    Here's an example:

    import tkinter as tk
    from tkinter import ttk
    
    def clear():
        for widget in combo_frame.winfo_children():
            if isinstance(widget, ttk.Combobox):
                widget.set("")
    
    root = tk.Tk()
    combo_frame = tk.Frame(root, bd=2, relief="groove")
    combo_frame.pack(side="top", fill="x")
    
    clear_button = tk.Button(combo_frame, text="clear", command=clear)
    clear_button.pack(side="top")
    for i in range(10):
        combo = ttk.Combobox(combo_frame, values=("one", "two", "three"))
        combo.pack(side="top", anchor="w")
    
    tk.mainloop()