尝试读取条目时读取错误

时间:2017-03-07 00:16:52

标签: python tkinter

首先,我想说清楚我是一个菜鸟,我知道这可能是写错误的方法(使用exec()语句)但是我无法将它们编入索引所以这是我提出的解决方案,如果你有替代方案,我很乐意改变代码。

但是,定义我的桌子的笨拙方式不是我在这里的原因(或者可能是因为我很容易因为它而犯了错误)。 当我尝试运行此代码时,一切顺利,直到最后一部分。我收到一条错误消息:'_tkinter.TclError:无效的命令名“。!entry”'我不知道它是什么以及如何解决它。

我的程序需要读取max_number_of_colors给出的一定数量的颜色并将其保存在列表中

这是我正在谈论的一段代码:

def get_entry_colors():
    global all_colors
    all_colors = []
    for i in range(1,max_number_of_colors+1):
        exec('all_colors['+str(i-1)+'] = int(E'+str(i)+'.get())')
    return
def get_colors(max_number_of_colors):
    """
     #define max_number_of_color fields with the same amount of entry boxes
    """
    global setup
    setup = Tk()
    setup.title("Mastermind - setup")
    for i in range(1,max_number_of_colors+1):
        exec('global E'+str(i))
    for i in range(1,max_number_of_colors+1):
        exec('label'+str(i)+' = Label(setup, text="color'+str(i)+':");E'+str(i)+' = Entry(setup, bd=5)')
    #define button
    submit = Button(setup, text='Submit', command=get_entry_colors)
    #draw the fields and entry boxes
    for i in range(1,max_number_of_colors+1):
        exec("label" + str(i) + ".pack();E" + str(i) + ".pack()")
    #draw button
    submit.pack(side=BOTTOM)
    setup.mainloop()

感谢您对此进行调查。

1 个答案:

答案 0 :(得分:2)

我没有使用exec而没有使用任意变量,而是为你重写了这个。别再这样做了。如果要存储一系列内容,请使用容器类型的单个实例,如列表或字典。

import Tkinter as tk

def get_entry_colors():
    all_colors = []
    for i in entry_list:
        all_colors.append(i.get())
    print(all_colors)

def get_colors(max_number_of_colors):
    """
     #define max_number_of_color fields with the same amount of entry boxes
    """
    global entry_list
    entry_list = []

    setup = tk.Tk()
    setup.title("Mastermind - setup")

    for i in range(1,max_number_of_colors+1):
        lbl = tk.Label(setup, text="color {}:".format(i))
        lbl.pack()
        ent = tk.Entry(setup, bd=5)
        ent.pack()
        entry_list.append(ent)
    #define button
    submit = tk.Button(setup, text='Submit', command=get_entry_colors)

    submit.pack()
    setup.mainloop()

get_colors(5)

使用global也有点不对劲;你应该试着摆脱这种习惯。