The OptionMenu and Combobox widgets

The OptionMenu and Combobox widgets are used to give the user the choice of one option from a group, much like a Radiobutton. They both display in a similar manner to a drop-down menu, or select menu, from HTML.

Whereas the OptionMenu widget only allows the user to choose an option that is in the menu, the Combobox widget essentially combines an Entry widget with the OptionMenu widget, allowing the user to type their own choice into the box as well.

We can have a look at these two widgets with a small piece of code:

import tkinter as tk
import tkinter.ttk as ttk

win = tk.Tk()

options = ("low", "medium", "high")
om_chosen = tk.StringVar()

To prepare for these two widgets, we need a Tkinter variable to store the selection of the OptionMenu and a tuple of options which will be applied to each.

When instantiating the OptionMenu, the arguments will be the following:

  • The parent widget (as usual)
  • The variable in which to store the chosen answer
  • The default answer
  • The selectable options

In contrast, when instantiating a Combobox, we only need the parent widget, followed by the selectable options as a keyword argument named options. Since the Combobox is not linked to a Tkinter variable, we have to obtain its selection by calling the get method on the widget directly.

om = ttk.OptionMenu(win, om_chosen, "medium", *options)

cb = ttk.Combobox(win, values=options)

om.pack()
cb.pack()

win.mainloop()

Here, we create an OptionMenu, passing it the StringVar we made earlier, the string medium as the default value, and all possible options are supplied by unpacking the tuple options.

We then create a Combobox with just the parent widget and the options keyword argument.

Give this file a run and have a play with both widgets:

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

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