【问题标题】:an error in entry in tkintertkinter 输入错误
【发布时间】:2016-12-18 14:35:49
【问题描述】:

我该怎么办? 我想获得一个条目,但这是什么错误??????

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 已定义,但它说它不是!!!!?

【问题讨论】:

  • 你确定e 是全局定义的,而不是在一个类或什么的?显示更多代码。
  • 你将e定义为函数p中的local变量

标签: python tkinter compiler-errors


【解决方案1】:

global 在函数内部用于通知函数使用外部/全局变量而不是本地变量。它不会创建全局变量。

要创建全局变量,您必须使用外部函数,即。

e = None    # or any other value

然后您必须在p() 中使用global e 来通知函数您要将Entry() 分配给外部/全局变量,并且函数不必创建局部变量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() 将创建全局变量(但global e 没有e = ... 将不会创建全局变量)。

有时最好使用e = None,因为它对于阅读您的代码的人来说可能是有用的信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2020-10-28
    • 2017-01-30
    • 2014-10-06
    • 2012-03-20
    相关资源
    最近更新 更多