2016-12-18 14 views
-1

どうすればいいですか? 私はエントリを取得したいが、このエラーは何ですか?tkinterの入力エラー

def gt(): 
    global e 
    string = e.get() 
    print(string) 
def p(): 
    b.destroy() 
    c.destroy() 
    w = Label(top, text="here are what you can use:") 
    w1 = Label(top, text="qwertyuiop[]asdfghjkl;zxcvbnm,./QWERTYUIOPASDFGHJKLZXCVBNM123456789") 
    w.pack() 
    w1.pack() 
    L1 = Label(top, text="give me the password") 
    L1.pack(side = LEFT) 
    e=Entry(top) 
    e.pack() 
    r = Button(top,text='okay',command=gt) 
    r.pack(side='bottom') 
    top.mainloop() 

エラー:

Traceback (most recent call last): 
    File "C:\Python33\lib\idlelib\run.py", line 121, in main 
    seq, request = rpc.request_queue.get(block=True, timeout=0.05) 
    File "C:\Python33\lib\queue.py", line 175, in get 
    raise Empty 
queue.Empty 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__ 
    return self.func(*args) 
    File "C:\Users\Hadi\Desktop\t.py", line 51, in gt 
    string = e.get() 
NameError: global name 'e' is not defined 

は、どのように私はこのコードを修正することができますか? eが定義されていますが、それは!!!!

+2

'e'はグローバルに定義されていますが、クラスなどでは定義されていませんか?より多くのコードを表示する。 – kabanus

+0

'e'を関数' p'の_local_変数として定義します –

答えて

0

globalは、ローカル変数の代わりに外部/グローバル変数を使用する関数に通知する関数内で使用されます。グローバル変数は作成されません。

グローバル変数を作成するには、関数ieの外部で使用する必要があります。

e = None # or any other value 

そしてあなたは、外部/グローバル変数や関数にあなたがEntry()を割り当てたい機能を知らせるためにp()global eを使用する必要がありますがe

# create global variable - you have to assign any value - ie. `None` 
e = None 

def gt(): 
    # global e # you don't need "global" because you doesn't assign new value using `=` 
    print(e.get()) 

def p(): 
    # inform function to use external/global variable instead of local one 
    global e # you need it because you use `=` to assign new value 

    e = Entry(top) 
    e.pack() 

ローカル変数を作成する必要がdoen't

BTW:global ee = Entry()がグローバル変数を作成するため、e = Noneをスキップすることもできます(ただし、global eなしでe = ...はグローバル変数を作成しません)。

コードを読む人にとって便利な情報になることがあるので、e = Noneをよく使うことがあります。