Assigning variables using choices in TKInter dropdown menu - Python 2.7 Assigning variables using choices in TKInter dropdown menu - Python 2.7 tkinter tkinter

Assigning variables using choices in TKInter dropdown menu - Python 2.7


Try following code. Read a comment I added.

from Tkinter import *import Tkinter as ttk from ttk import *root = Tk()root.title("Age Selector")mainframe = Frame(root)                                 mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )mainframe.columnconfigure(0, weight = 1)mainframe.rowconfigure(0, weight = 1)mainframe.pack(pady = 10, padx = 10)var = StringVar(root)# Use dictionary to map names to ages.choices = {    'Bob': '35',    'Garry': '45',    'John': '32',    'Hank': '64',    'Tyrone': '21',}option = OptionMenu(mainframe, var, *choices)var.set('Bob')option.grid(row = 1, column =1)Label(mainframe, text="Age").grid(row = 2, column = 1)age = StringVar()# Bind age instead of varage_ent = Entry(mainframe, text=age, width = 15).grid(column = 2, row = 2)# change_age is called on var change.def change_age(*args):    age_ = choices[var.get()]    age.set(age_)# trace the change of varvar.trace('w', change_age)root.mainloop()

According to the documentation:

trace(mode, callback) => string

Add a variable observer. Returns the internal name of the observer (you can use this to unregister the observer; see below).

The mode argument is one of “r” (call observer when variable is read by someone), “w” (call when variable is written by someone), or “u” (undefine; call when the variable is deleted).