我尝试在python 3.6中修改此脚本,但是我有一个关于标签未显示在底部的问题。这是代码:
from tkinter import *
def sel():
global selection
if value==1:#value and var1 are in radiobutton R1
selection = "You selected the option " + str(var1.get())
elif value==2:#value and var2 are in radiobutton R2
selection = "You selected the option " + str(var2.get())
elif value==3:#value and var3 are in radiobutton R3
selection = "You selected the option " + str(var3.get())
label.config(text = selection)
root = Tk()
root.geometry('350x250')
value=IntVar()
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var1, value=1,
command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var2, value=2,
command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var3, value=3,
command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
当我选择其中一个单选按钮时,标签通常应显示在下方,但不显示在单选按钮的底部,并且出现此错误:
NameError:名称“选择”未定义
答案 0 :(得分:0)
“值”的值永不变。这意味着您调用的函数不会给选择任何值。由于选择没有任何价值,但是无论如何都会使用它,所以会出现nameError。
我希望在这样的按钮命令中使用lambda:
from tkinter import *
def sel(value):
selection = "You selected the option {}".format(value)
label.configure(text=selection)
root = Tk()
root.geometry('350x250')
selection = "StartText"
R1 = Radiobutton(root, text="Option 1",command=lambda: sel(1))
R1.pack()
R2 = Radiobutton(root, text="Option 2",command=lambda: sel(2))
R2.pack()
R3 = Radiobutton(root, text="Option 3",command=lambda: sel(3))
R3.pack()
label = Label(root, text=selection)
label.pack()
root.mainloop()