Search code examples
pythontkintertkinter-button

Trying to create a return to home screen button using Tkinter, getting not defined traceback


I am trying to code a return to home screen button while closing the current window but I am getting "newWindow is not defined". I am able to navigate to new menus while closing the home screen but not the other way around.

def cardinfobutt() works but def home() doesnt

Heres my code:

root = Tk()

def home():
    root = Tk()
    root.geometry("600x300")
    root.maxsize(600, 300)
    root.minsize(600, 300)
    root.title("eBot")
    newWindow.destroy()

def cardinfobutt():
    newWindow = Tk()
    newWindow.title("Card Information")
    newWindow.geometry("600x300")
    Label(newWindow, text="Card Information").pack()
    homebutton = Button(newWindow, text="Back to Home Screen", padx=50, pady=50, command=home, fg="black", bg="white")
    homebutton.pack()
    root.destroy()

tried to use the same process home screen -> other menus, get newWindow is not defined.

def cardinfobutt() works but def home() doesnt.


Solution

  • The newWindow.destroy() and root.destroy() will destroy both windows simultaneously.

    What you are looking for :

    • root.update()
    • root.deiconify()
    • newWindow.destroy()

    Edit: I added global and root.withdraw() in home() function. I modified your code and added widgets.

    Snippet:

    import tkinter as tk
    
      
    def home():
        global newWindow
        root.withdraw()
        newWindow = tk.Toplevel()
        newWindow.geometry("600x300")
        tk.Label(newWindow, text="Card Information").pack()
        homebutton = tk.Button(newWindow, text="Back to Home Screen", padx=50, pady=50, command=show, fg="black", bg="white")
        homebutton.pack()
          
    
    def show():
        root.update()
        root.deiconify()
        newWindow.destroy()
     
    root = tk.Tk()
    root.geometry("600x300")
    root.maxsize(600, 300)
    root.minsize(600, 300)
    root.title("eBot")
     
         
    mybutton = tk.Button(root, text = "New Window", command = home)
    mybutton.pack(pady = 10)
     
    root.mainloop()
    

    Screenshot:

    enter image description here