首页 > 解决方案 > 标签未显示在 tkinter

问题描述

我尝试在 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:名称“选择”未定义

标签: python-3.xtkinter

解决方案


“价值”的价值永远不会改变。这意味着您调用的函数永远不会给选择任何值。由于选择没有价值,但无论如何你都会使用它,你会得到一个 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()

推荐阅读