2017-03-07 3 views
-1

まず最初に、私が新人であることを明確にしたいと思います。これはおそらくこれをexec()文で書くのは間違った方法ですインデックスを作成できなかったため、これが私が思いついた解決策でした。代替案がある場合は、コードを変更して幸いです。エントリからの読み取りを読み込もうとするとエラーが発生する

私のテーブルを定義する不器用な方法は、私がここにいる理由ではありません(または、おそらく私はそれが原因で簡単に間違えたかもしれないからです)。 このコードを実行しようとすると、最後まですべてがうまく行きます。 '_tkinter.TclError:無効なコマンド名です。'というエラーメッセージが表示され、それが何であり、どのように解決するのか分かりません。

私のプログラムは、これは私が話しているコードの一部である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を使用せずに、任意の変数を使用せずにこれを書き換えました。もはやそれをしないでください。一連のものを格納する場合は、リストや辞書のようなコンテナタイプの単一インスタンスを使用します。 globalを使用して

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) 

はあまりにも多少悪いです。あなたはその習慣から脱出しようとするべきです。

+0

ありがとうございます。本当に感謝。私はラベルとエントリを持つリストを作成する方法を理解できませんでした。これは多くの助けになります! – nomis6432

関連する問題