【问题标题】:Changing text of labels defined in a loop更改循环中定义的标签文本
【发布时间】:2017-12-08 13:15:42
【问题描述】:

我正在尝试制作一个可扩展的计数器。

在第一个窗口中输入所需的计数器数量。

在第二个窗口中有标签和按钮,用于向标签添加一个。

这是我的代码:

from tkinter import *

root = Tk()

def newWindow():
    window = Toplevel()
    for i in range(int(textbox.get())):
        exec("global label"+ str(i))
        exec("label" + str(i) + " = Label(window, text = '0')")
        exec("label" + str(i) + ".grid(row = 0, column = i)")
        exec("global button"+ str(i))
        exec("button" + str(i) + " = Button(window, text = 'Add', command = lambda: setText(label" + str(i) + "))")
        exec("button" + str(i) + ".grid(row = 1, column = i)")

def setText(label):
    label.config(text = str(int(label.cget("text")) + 1))

textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)

root.mainloop()

然而,这是我得到的错误:

name 'label_' is not defined

其中 _ 是 i。

使它们全球化也没有解决这个问题。

请帮忙!

【问题讨论】:

  • 请显示完整的错误信息。

标签: python button tkinter label counter


【解决方案1】:

如果你以这种方式使用exec,那你就做错了。

简单的解决方案是将小部件添加到列表或字典中。但是,在这种特定情况下,您不需要它,因为除了按钮命令之外,您从未在任何地方引用标签。

这是一个工作示例:

from tkinter import *

root = Tk()

def newWindow():
    global labels
    window = Toplevel()
    labels = {}
    for i in range(int(textbox.get())):
        label = Label(window, text='0')
        button = Button(window, text='Add', command = lambda l=label: setText(l))

        label.grid(row=0, column=i)
        button.grid(row=1, column=i)

        # this allows you to access any label later with something
        # like labels[3].configure(...)
        labels[i] = label

def setText(label):
    label.config(text = str(int(label.cget("text")) + 1))

textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)

root.mainloop()

如果你想使用labels,你可以让你的按钮传入索引,然后让setText从字典中获取小部件:

def setText(i):
    label = labels[i]
    label.configure(...)
...
button = Button(..., command=lambda i=i: setText(i))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多