Search code examples
pythontkinter

How to detect a dropdown in a ttk:comboBox?


I'm trying to figure out how to detect that a dropdown has been triggered. The reason is that I would like to update/refresh the dropdown-lists contents when this happens. I have found that

"ComboBoxSelected"

is the only event that can be binded? Any ideas out there?

I've just tried to bind standard widget events but have not succussed (as the newbie I am)


Solution

  • You can use postcommand option of ttk::Combobox to call a function before showing the dropdown and set the values of the dropdown inside that function.

    Below is an example:

    import random
    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    
    choices = [f'Choice #{i}' for i in range(1, 20)]
    
    def before_post():
        values = random.choices(choices, k=5)
        combo.config(values=values)
    
    combo = ttk.Combobox(root, postcommand=before_post, state='readonly')
    combo.pack(padx=20, pady=10)
    
    root.mainloop()