How it works...

As usual, the ttk.Combobox widget is added to our application by passing the Tk instance as the first parameter to its constructor. The values option specifies the list of selectable choices that are displayed when the drop-down arrow is clicked.

We bind the "<<ComboboxSelected>>" virtual event that is generated when one of the choices from the list of values is selected:

        self.label = ttk.Label(self, text="Please select a color")
self.combo = ttk.Combobox(self, values=colors)
btn_submit = ttk.Button(self, text="Submit",
command=self.display_color)
btn_clear = ttk.Button(self, text="Clear",
command=self.clear_color)

self.combo.bind("<<ComboboxSelected>>", self.display_color)

The same method is invoked when you click on the Submit button, so it receives a value input by the user.

We defined that display_color() takes a variable list of arguments using the * syntax to safely handle optional arguments. This happens because an event is passed to it when invoked through event binding, but it does not receive any parameters when invoked from the button callback.

Within this method, we retrieve the current Combobox value via its get() method and print it in the standard output:

    def display_color(self, *args):
color = self.combo.get()
print("Your selection is", color)

Finally, clear_color() clears the contents of the Combobox by calling its set() method with the empty string:

    def clear_color(self):
self.combo.set("")

With these methods, we have explored how to interact with the current selection of a Combobox instance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset