尝试以下代码.阅读我添加的评论.
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 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()
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).