I want to switch frames in Python tkinter, but I get a maximum recursion depth exceeded error.

Asked 2 years ago, Updated 2 years ago, 87 views

from tkinter import *

class myApp(Tk):

    def changeFrame(self, classParam):
        # # if self.nowFrame:
        #     #     self.NowFrame.destory()# An error occurs in this part.
        self.nowFrame = classParam
        self.nowFrame.pack()

    def __init__(self, root):
        myMenu=Menu(root)
        menu1=Menu(myMenu)
        menu1.add_command(label="before", command=rambda:self.changeFrame(frameClass_1())))
        menu1.add_command(label="next", command=rambda:self.changeFrame(frameClass_2())))
        myMenu.add_cascade(label="frame switching", menu=menu1)
        root.config(menu=myMenu)
        root.mainloop()



class frameClass_1(Frame):
    def __init__(self):
        super().__init__()
        Label(self, text="frame1").pack()



class frameClass_2(Frame):
    def __init__(self):
        super().__init__()
        Label(self, text="frame2").pack()

root = Tk()
myApp(root)

If you select the previous menu, you want to switch to Frame 1, and if you select the next menu, you want to switch to Frame 2.

However, if you select the menu, the error below appears. How do we solve this?

[Previous line repeated 989 more times]
RecursionError: maximum recursion depth exceeded

python tkinter

2022-09-20 15:08

1 Answers

Resolved in stack overflow.

import tkinter as tk

class myApp(): # No need to inherit Tk.

    def switchFrame(self, classParam):
        if self.NowFrame: # It's not destory, it's destroy
            self.nowFrame.destroy()
        self.nowFrame = classParam
        self.nowFrame.pack()


    def __init__(self, root):
        self.NowFrame = None # NowFrame must be initialized.
        myMenu=tk.Menu(root)
        menu1=tk.Menu(myMenu)
        menu1.add_command(label="before", command=lambda:self.switchFrame(frameClass_1()))
        menu1.add_command(label="next", command=lambda:self.switchFrame(frameClass_2()))
        myMenu.add_cascade(label="switch", menu=menu1)
        root.config(menu=myMenu)
        root.mainloop()



class frameClass_1(tk.Frame):
    def __init__(self):
        super().__init__()
        tk.Label(self, text="frame1").pack()



class frameClass_2(tk.Frame):
    def __init__(self):
        super().__init__()
        tk.Label(self, text="frame2").pack()

root = tk.Tk()
myApp(root)



2022-09-20 15:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.