'Associate dropdown vars to tkinter entry and update said entry without pressing any buttons

from tkinter import *
import tkinter as ttk 


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': '1',
    'Garry': '2',
    'John': '3',
    'Hank': '4',
    'Tyrone': '5',
}

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 var
age_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 var
var.trace('w', change_age)

root.mainloop()

I've found this code on this site which is very descriptive of my problem.

This codes associates the choices dictionary values with age_ent entry. Every time the user chooses a dictionary key, the corresponding value is displayed in the entry box.

What I'm trying to do is whenever I'm typing in the age_ent entry the value is saved on the dictionary choices and can be later accessed by the drop-down menu. I'm trying to do this without the use of any buttons. Is it possible?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source