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

最佳答案

对于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

关于python - 为什么会收到错误:“NameError:未定义全局名称'pupiluserinputbox'”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22355401/

10-12 23:13