我正在尝试使用python中的单选按钮为变量赋值,其代码如下:
def print_me():
global payment
global membership
if studentMemString == "PY_VAR0":
membership = "STUDENT"
payment = studentMem
elif adultMemString == "PY_VAR10":
membership = "ADULT"
payment = adultMem
elif childMemString == "PY_VAR0":
membership = "CHILD"
payment = childMem
else:
pass
print(membership)
print(payment)
root = tk.Tk()
studentMem = tk.StringVar()
studentMemString = str(studentMem)
adultMem = tk.StringVar()
adultMemString = str(adultMem)
childMem = tk.StringVar()
childMemString = str(childMem)
studentRadBtn = tk.Radiobutton(root, text="Student - £19.99",
variable=studentMem, value= 19.99)
studentRadBtn.pack()
adultRadBtn = tk.Radiobutton(root, text="Adult - £34.99", variable=adultMem,
value= 34.99)
adultRadBtn.pack()
childRadBtn = tk.Radiobutton(root, text="Child - £5.99", variable=childMem,
value=5.99)
childRadBtn.pack()
button = tk.Button(root, text="click", command=print_me)
button.pack()
root.mainloop()
(更新)好的现在问题是,当我启动程序时,所有单选按钮都处于活动状态,无论我尝试单击哪一个,所以只有一个被调用是第一个。他们为什么都被选中了?
答案 0 :(得分:0)
在下面的代码中,radiobuttons在选择时更改变量v
的值。 v
的初始值为"2"
,因此默认情况下会选择第二个radiobutton。
import tkinter as tk
root = tk.Tk()
v = tk.StringVar()
v.set("2")
tk.Label(root, textvariable=v).pack()
tk.Radiobutton(root, text="one", variable=v, value="1").pack()
tk.Radiobutton(root, text="two", variable=v, value="2").pack()
tk.Radiobutton(root, text="three", variable=v, value="3").pack()
root.mainloop()