只需使用tk.Label() 小部件及其textvariable 参数将StringVar 绑定到它。每当附加的StringVar 更新时,标签会相应地更改其内容:
import random
import tkinter as tk
def roll(n):
return random.randint(1, n)
def calc():
thing = var.get()
if (thing == 'Barbarian'):
print ()
root = tk.Tk()
root.geometry("%dx%d+%d+%d" % (500, 80, 200, 150))
root.title("Gold Calculator")
selection = tk.StringVar(root)
selection.set('-Select a class-')
choices = ['Barbarian', 'Bard', 'Cleric', 'Druid', 'Fighter', 'Monk', 'Paladin', 'Ranger', 'Rougue', 'Sorcerer', 'Warlock', 'Wizard']
option = tk.OptionMenu(root, selection, *choices)
option.pack(side='left', padx=10, pady=10)
button = tk.Button(root, text="Calculate Gold", command=calc)
button.pack(side='left', padx=20, pady=10)
label = tk.Label(root, textvariable=selection)
label.pack(side='left', padx=20, pady=10)
root.mainloop()
既然我们已经完成了这项工作,我们可以看看如何在标签小部件中获取依赖于选择的文本。为此,我们可以连接一个回调函数,该函数观察与 OptionMenu 小部件连接的 StringVar。在该回调中,我们可以将当前内容作为键读取,并将标签小部件的所需内容作为值从 dict 中获取。
详情请查看代码中的 cmets:
import random
import tkinter as tk
def roll(n):
return random.randint(1, n)
def calc():
thing = var.get()
if (thing == 'Barbarian'):
print ()
# define a callback function in order to set the content of the label widget dependent on the selection
# reads the current content of StringVar `selection`, gets the desired value from the dict `d` and
# writes it to the StringVar `view_text`
def observe_option_menu(*args):
view_text.set(d.get(selection.get()))
root = tk.Tk()
root.geometry("%dx%d+%d+%d" % (550, 80, 200, 150))
root.title("Gold Calculator")
# create another StringVar and connect a callback function to it.
# hence trance as the 'w' flag, this callback will be fired whenever someone writes to the variable
selection = tk.StringVar(root)
selection.set('-Select a class-')
selection.trace('w', observe_option_menu)
choices = ['Barbarian', 'Bard', 'Cleric', 'Druid', 'Fighter', 'Monk', 'Paladin', 'Ranger', 'Rougue', 'Sorcerer', 'Warlock', 'Wizard']
# lists `texts` contains sample data in order to get key-value-pairs to combine selection with text of label
texts = ['VniC', '3DhO', 'CWm0', '8Cf9', 'avNN', 'SUnD', 'lp3R', 'Gtgk', 'FwvV', 'XzH1', 'CyGO', 'UASr']
# create a dict `d` out from the lists given above, you could use a dict directly instead of two seperate lists
d = dict(zip(choices, texts))
view_text = tk.StringVar(root)
view_text.set('Content depends on selection')
option = tk.OptionMenu(root, selection, *d.keys())
option.pack(side='left', padx=10, pady=10)
button = tk.Button(root, text="Calculate Gold", command=calc)
button.pack(side='left', padx=20, pady=10)
# create a Label widget `label` and place it using pack geometry manager
label = tk.Label(root, textvariable=view_text)
label.pack(side='left', padx=20, pady=10)
root.mainloop()