我是tkinter和面向对象编程的新手。出于某种原因,当运行以下代码并输入admin / password而不是切换帧时,它会出现以下错误:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args) File "H:\Networ\multiwindowguiskeleton.py", line 44, in checkpassword
controller.show_frame(messagescreenpagevar)
NameError: name 'controller' is not defined
代码是:
import tkinter as tk
class Guiroot(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
framecontainer = tk.Frame(self)
framecontainer.pack(side="top",fill="both",expand=True)
framecontainer.grid_rowconfigure(0,weight=1)
framecontainer.grid_columnconfigure(0,weight=1)
self.title("Vault Messenger")
self.frames = {}
passwordpagevar = passwordpage(framecontainer,self) # this is adding the different pages to a list so they can be called forward later.
messagescreenpagevar = messagescreen(framecontainer,self)
self.frames[passwordpagevar] = passwordpagevar
self.frames[messagescreenpagevar] = messagescreenpagevar
passwordpagevar.grid(row=0 , column = 0, sticky = "nsew")
messagescreenpagevar.grid(row=0 , column = 0, sticky = "nsew")
self.show_frame(passwordpagevar)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class passwordpage(tk.Frame):
def checkpassword(self):
if self.usernamebox.get() == "admin" and self.passwordbox.get() == "password":
self.errorlabel['text'] = "Correct entry/pass"
controller.show_frame(messagescreenpagevar)
else:
self.errorlabel['text'] = "Incorrect entry/pass"
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.usernamelabel = tk.Label(self,text="Username:")
self.usernamebox = tk.Entry(self)
self.passwordlabel = tk.Label(self, text="Password:")
self.passwordbox = tk.Entry(self,show="*")
self.errorlabel = tk.Label(self, text = "")
self.enterdetails = tk.Button(self, text = "Enter", command = self.checkpassword)
self.usernamelabel.grid(row=0)
self.usernamebox.grid(row=1)
self.passwordlabel.grid(row=2)
self.passwordbox.grid(row=3)
self.errorlabel.grid(row=4)
self.enterdetails.grid(row=5)
class messagescreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.userlist = tk.Listbox(self, width = 20, height = 20)
self.chatbox = tk.Text(self, width = 50,height = 20)
self.chatentry = tk.Entry(self, width = 60)
self.sendmessagebutton = tk.Button(self, text = "Send")
self.userlist.grid(row=0,column=0)
self.chatbox.grid(row=0,column=1, columnspan = 2)
self.chatentry.grid(row=1,column=1)
self.sendmessagebutton.grid(row=1,column= 2)
root = Guiroot()
root.mainloop()
答案 0 :(得分:1)
在第44行,解释器找到以下表达式
TClientDataset
在此范围内,未定义controller.show_frame(messagescreenpagevar)
。这就是解释器提示错误controller
。
Python使用词法范围。因此,为了在第44行定义变量name 'controller' is not defined
,您必须在以下位置定义它:
controller
checkpassword