【问题标题】:label not displayed in tkinter标签未显示在 tkinter
【发布时间】:2018-12-17 18:54:07
【问题描述】:

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

【问题讨论】:

  • 您可以在全局范围内声明selection,也可以在sel() 内将global selection 更改为selection = ""

标签: python-3.x tkinter


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多