I have a program that performs frame switching like in this example: Switch between two frames in tkinter
I am trying to make part of my program switch frames through a function, where the command to switch frames is inside another function, rather than the button.
This is the switch frame function:
class MathsApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame=None
self.switch_frame(StartPage)
self.title("Maths Revision App")
self.geometry("800x500")
self.configure(bg="white")
def switch_frame(self, frame_class):
#Destroys current frame and replaces it with a new one.
new_frame=frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame=new_frame
self._frame.pack(fill="both",expand=True)
This is the function that I am trying to get to switch frames:
def validateAns(ans):
global questionpages,currentQ
if ans=="":
self.switch_frame(errorPage)
else:
if currentQ==9:
checkAns(ans, currentQ)
getTimes()
self.switch_frame(ResultPage)
else:
checkAns(ans, currentQ)
getTimes()
currentQ=currentQ+1
self.switch_frame(questionpages[currentQ])
Everything else with this function works except the switch_frame lines.
This is one of the frames that uses this function:
class q1(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master, bg="white")
lbl=tk.Label(self, text="Question 1", font=title_font, bg="white", fg="#004d99")
lbl.place(x=30, y=20)
txt=tk.Text(self, height=7, width=70)#the text box that displays the question
txt.config(state="normal")
txt.insert(tk.INSERT,qlist[0][0])
txt.config(state="disabled")
txt.place(x=35,y=125)
ans=tk.Entry(self)
ans.place(x=650, y=350,height=25)
btn=tk.Button(self, text="Next", height=3, width=15, fg="white", bg="#004d99", command=lambda:validateAns(ans.get()))
btn.place(x=650, y=400)
When I click the button on frame q1 that uses "validateAns" I get the error message "name 'self' not defined". I tried replacing self.switch_frame with "master.switch_frame" and got a similar error, but with 'master' not being defined.
Depending on the value passed into the validateAns function, the page/frame should switch to one of three different ones.