【问题标题】:Why do I get the error: "NameError: global name 'pupiluserinputbox' is not defined"为什么我会收到错误消息:“NameError:未定义全局名称'pupiluserinputbox'”
【发布时间】:2014-03-12 14:57:42
【问题描述】:
def pupiluserpass():
    global usernames, passwords
    usernameinp = pupiluserinputbox.get()
    passwordinp = pupilpasswordinputbox.get()

为什么会出现错误:NameError: global name 'pupiluserinputbox' 未定义?

输入框在另一个过程中:

def pupillogin():
   ruapupil = Label(app, text = "If you're a pupil log in here:")
   ruapupil.grid(row = 1, columnspan = 3, sticky = W)

   pupilusername = Label(app, text = "Please enter your Username:")
   pupilusername.grid(row = 2, column = 0, sticky = W)
   pupiluserinputbox = Entry(app, width = 10)
   pupiluserinputbox.grid(row = 2, column = 1, sticky = W)

   pupilpassword = Label(app, text = "Please enter your Password:")
   pupilpassword.grid(row = 3, column = 0, sticky = W)
   pupilpasswordinputbox = Entry(app, width = 10)
   pupilpasswordinputbox.grid(row = 3, column = 1, sticky = W)

   pupilenter = Button(app, text = "Enter!", command = pupiluserpass)
   pupilenter.config(height = 1, width = 8)
   pupilenter.grid(row = 4, column = 1, sticky = W) 

我怎样才能成功地完成这项工作而不得到NameError

【问题讨论】:

  • 在一个函数中定义的变量在单独的函数中不可见。使用global 变量或将函数放在一个类中并将值作为属性分配给self
  • +1 用于后一种解决方案 ;-)

标签: python python-3.x tkinter nameerror


【解决方案1】:

对于class,您应该将携带这些错误属性的变量设置为self,即该对象的当前实例。这是在class 中的其他方法中访问这些变量的事实上的方式。例如:

def pupiluserpass():
    ...
    usernameinp = self.pupiluserinbox.get()
    passwordinp = self.pupilpasswordinputbox.get()

def pupillogin():
    ...
    self.pupiluserinputbox = Entry(app, width = 10)
    self.pupiluserinputbox.grid(row = 2, column = 1, sticky = W)
    ...
    self.pupilpasswordinputbox = Entry(app, width = 10)
    self.pupilpasswordinputbox.grid(row = 3, column = 1, sticky = W)

你也可以在这里做很多global声明,但最好使用self

【讨论】:

  • 使用 self 我得到这个错误:NameError: global name 'self' is not defined
  • 您的代码是class 格式吗?如果不是,那么它需要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 2014-03-07
  • 1970-01-01
相关资源
最近更新 更多