我正在尝试为超简单的自动售货机编写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)
我浏览过该网站,但没有找到任何具体解决此问题的内容。
答案 0 :(得分:2)
chocchoice
has to be StringVar()
, not normal variable because all variable=
and textvariable=
expects StringVar()
, IntVar()
, etc.
chocchoice = StringVar(value="s")
And then you need to use .get()
c = chocchoice.get()
BTW: because you don't assign new value to chocchoice
using =
then you don't have to use global chocchoice
in function.
EDIT: shorter version
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()