2017-03-07 29 views
-1

首先,我想明确表示我是菜鸟,并且我知道这可能是用exec()语句写出来的错误方法,但我无法为它们编制索引,所以这是我提出的解决方案,如果您有其他解决方案,我会很乐意更改代码。尝试从条目中读取时出错

但是,定义我的表的笨拙方式不是我在这里的原因(或者也许是因为我很容易因为它而犯了一个错误)。 当我尝试运行这段代码时,一切都很顺利,直到最后一部分。我收到一条错误消息:'_tkinter.TclError:invalid command name'。!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() 

谢谢为了研究这一点。

+3

你应该忘记'exec'的存在。将数据存储在列表和字典中并循环播放。那么你的问题会自行解决。 – Novel

回答

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也有些不好;你应该尝试摆脱这种习惯。

+0

谢谢。非常感谢。我无法弄清楚如何创建一个带有标签和条目的列表。这有助于很多! – nomis6432

相关问题