更改循环中定义的标签文本

时间:2017-12-08 13:15:42

标签: python button tkinter label counter

我试图制作一个可扩展的计数器。

在第一个窗口中输入您想要的计数器数量。

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

这是我的代码:

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

其中_是我。

让它们全球化并没有解决这个问题。

请帮忙!

1 个答案:

答案 0 :(得分:0)

如果您以这种方式使用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))
相关问题