Skip to content Skip to sidebar Skip to footer

Bind Tkinter Combobox To Entry Change?

I have a ttk.Combobox that my users can select from a dropdown list of options, or manually type something in. I have it bound to Return, so that if my user presses return after ma

Solution 1:

ttk.Comboboxes are a subclass of Entry widgets, which means that you can add validation to them in the same manner as you would to their base class. Namely by using the validate= and validatecommand= options Entrys support.

The reason to do this is because "validation" will allow the contents of the associated Combobox to be checked when it loses focus—i.e. your stated goal. This should work fine in conjunction with the bound event-handling you already have. The following code, which is similar to your minimal reproducible example, illustrates how do to something like that.

Note: This approach would also allow doing some real validation of the values the user has entered to prevent problems later on if they're invalid.

import tkinter as tk
from tkinter import ttk

defupdate(updated_entry, entry):
    ''' Combobox change Callback. '''
    entry.delete('1.0', tk.END)
    entry.insert(tk.END, updated_entry)

defgui(root):
    root.geometry('300x150')
    root.config(background='snow3')

    for row inrange(2):
        text = tk.Text(root, height=1, width=10)  # Widget to be updated.
        text.grid(row=row, column=2)

        defcheck_okay(new_value, text=text):
            update(new_value, text)
            returnTrue# Note: accepts anything.

        combobox = ttk.Combobox(root, value=('test', 'test1', 'test2'),
                                validate='focusout',
                                validatecommand=(root.register(check_okay), '%P'))
        combobox.grid(row=row, column=1)

        combobox.bind('<Return>', lambda event, entry=combobox, text=text:
                                    update(entry.get(), entry=text))
        combobox.bind('<<ComboboxSelected>>', lambda event, entry=combobox, text=text:
                                                update(entry.get(), entry=text))

if __name__ == '__main__':
    root = tk.Tk()
    gui(root)
    tk.mainloop()

Post a Comment for "Bind Tkinter Combobox To Entry Change?"