Here we use a drop-down menu widget as a way to select one item from a choice of several on offer.
Execute the program shown in the usual way. The result is shown in the following screenshot:
# dropdown_1.py # >>>>>>>>>>>>>>>>>>> from Tkinter import * root = Tk() root.title("Drop-down boxes for option selections.") var = StringVar(root) var.set("drop down menu button") def grab_and_assign(event): chosen_option = var.get() label_chosen_variable= Label(root, text=chosen_option) label_chosen_variable.grid(row=1, column=2) print chosen_option drop_menu = OptionMenu(root, var, "one", "two", "three", "four", "meerkat", "12345", "6789", command=grab_and_assign) drop_menu.grid(row=0, column=0) label_left=Label(root, text="chosen variable= ") label_left.grid(row=1, column=0) root.mainloop()
The drop-down menu has its own button. The callback()
function that gets called when this button is clicked is named grab_and_assign
in this particular recipe and one of the instructions in this event service routine is to assign the value of the menu item selected to the variable chosen_option
. The instruction that does this is chosen_option = var.get()
.
As we did previously, we reassure ourselves that everything works as expected by printing the new value of chosen_option
as a label on the parent window.
3.138.35.255