为什么我会收到错误:" NameError:全局名称' pupiluserinputbox'没有定义"

时间:2014-03-12 14:57:43

标签: python python-3.x tkinter nameerror

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

1 个答案:

答案 0 :(得分: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