为何出现错误:“NameError: global name 'pupiluserinputbox' is not defined”?

1 投票
1 回答
560 浏览
提问于 2025-04-17 21:57
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 个回答

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 更好。

撰写回答