我该怎么办? 我想要一个条目,但是这个错误是什么?????
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已定义,但它表示它不是!!!!?
答案 0 :(得分:0)
global
来通知函数使用外部/全局变量而不是本地变量。它不会创建全局变量。
要创建全局变量,您必须使用外部函数,即
e = None # or any other value
然后你必须在global e
中使用p()
来告知函数你要将Entry()
分配给外部/全局变量,而函数不必创建局部变量{{ 1}}
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()
,因为e = None
加global e
会创建全局变量(e = Entry()
with global e
不会创建全局变量)。
有时候更好地使用e = ...
,因为它可以为读取您的代码的人提供有用的信息。