[英]Updating Tkinter Labels using StringVar
我正在尝试为超简单的自动售货机编写GUI,但是在使用单选按钮进行选择后,我无法更新标签。 相反,当按下单选按钮时,无论选择什么,它都会将标签设置为默认值。
这是我的代码:
from tkinter import *
import tkinter as tk
#Native Functions
def f_Update():
global chocchoice
global price
c = chocchoice
if c == "m":
price = 60
chocprice.set(price)
chocname.set("You have chosen - Mars")
if c == "t":
price = 70
chocprice.set(price)
chocname.set("You have chosen - Twix")
if c == "mw":
price = 65
chocprice.set(price)
chocname.set("You have chosen - Milky Way")
if c == "s":
price == 80
chocprice.set(price)
chocname.set("You have chosen - Snickers")
root =tk.Tk()
#Let's declare some variables!
chocchoice = "s"
price = 0
chocprice = StringVar()
chocname = StringVar()
summary = StringVar()
#Actual Code
frame = tk.Frame(root,
height = 300,
width = 800)
frame.pack()
L1 = tk.Label(root,
text = "Please select a chocolate bar:",
bg = "white")
L1.place(x=10, y=10)
Radiobutton(root,
text="Mars",
padx = 10,
variable = chocchoice,
value = "m",
command = f_Update).place(x=10,y=40)
Radiobutton(root,
text="Twix",
variable = chocchoice,
value = "t",
command = f_Update).place(x=10, y=70)
Radiobutton(root,
text="Milky Way",
variable = chocchoice,
value = "mw",
command = f_Update).place(x=10, y=100)
Radiobutton(root,
text="Snickers",
variable = chocchoice,
value = "s",
command = f_Update).place(x=10, y=130)
L2 = tk.Label(root,
textvariable = chocname ,
bg = "white")
L2.place(x=350,y=10)
L3 = tk.Label(root,
textvariable = chocprice,
bg = "white")
L3.place(x=350,y=40)
我浏览了该网站,但没有找到能解决此问题的任何东西。
chocchoice
必须是StringVar()
,而不是常规变量,因为所有variable=
和textvariable=
期望StringVar()
, IntVar()
等。
chocchoice = StringVar(value="s")
然后您需要使用.get()
c = chocchoice.get()
顺便说一句:因为您不必使用=
来为chocchoice
分配新值, chocchoice
您不必在函数中使用global chocchoice
。
编辑:较短的版本
import tkinter as tk
# --- functions ---
def update():
c = choc_choice.get()
if c in products:
price, name = products[c]
choc_price.set(price)
choc_name.set(name)
# --- data ---
products = { # key: [price, name],
"m": [60, "Mars"],
"t": [70, "Twix"],
"mw": [65, "Milky Way"],
"s": [80, "Snickers"],
}
# --- main ---
root = tk.Tk()
# variables (have to be after tk.Tk())
choc_choice = tk.StringVar()
choc_name = tk.StringVar(value="- none -")
choc_price = tk.IntVar()
summary = tk.IntVar()
# left side
left_frame = tk.Frame(root)
left_frame.grid(row=0, column=0, padx=5)
tk.Label(left_frame, text="Please select a chocolate bar:").pack()
for key, val in products.items():
price, name = val
tk.Radiobutton(left_frame, text=name, value=key, anchor='w',
variable=choc_choice, command=update).pack(fill='x')
# right side
right_frame = tk.Frame(root)
right_frame.grid(row=0, column=1, sticky='n', padx=5)
tk.Label(right_frame, text="You have chosen:").pack()
tk.Label(right_frame, textvariable=choc_name).pack()
tk.Label(right_frame, textvariable=choc_price).pack()
# start
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.