Search code examples
pythontkintertkinter-layouttkinter-buttontkinter.text

How to switch between two tkinter frames


enter image description here
I am trying to switch and display two frames in tkinter using the codes below but I am not succeeding. I have attached an image of what the code is displaying.

from tkinter import*
    root= Tk()
    root.title("HOSPITAL MANAGEMENT SYSTEM")
    root.geometry('600x350')
    #=======frames====
    HR=Frame(root)
    Schain=Frame(root)
    #=========================functions for switching the frames========
    def change_to_HR():
        HR.pack(fill='BOTH', expand=1)
        Schain.pack_forget()
        def change_to_Schain():
            Schain.pack(fill='BOTH', expand=1)
            HR.pack_forget()
        #=====================Add heading logo in the frames======
        labelHR=Label(HR, text="HR DEPARTMENT")
        labelHR.pack(pady=20)
    
        labelSchain=Label(Schain, text="SUPPLY CHAIN DEPARTMENT")
        labelSchain.pack(pady=20)
        #===============================add button to switch between frames=====
        btn1=Button(root, text="HR", command=change_to_HR)
        btn1.pack(pady=20)
        btn2=Button(root, text="SUPPLY CHAIN", command=change_to_Schain)
        btn2.pack(pady=20)
    root.mainloop()

Solution

  • The mistake is in the following lines:

    HR.pack(fill='BOTH', expand=1)
    Schain.pack(fill='BOTH', expand=1)
    

    You must either directly give the string in lowercase as 'both' or use the pre-defined tkinter constant BOTH. On changing 'BOTH' to BOTH in both the places, your code works properly.


    Working Code:

    from tkinter import *
    root= Tk()
    root.title("HOSPITAL MANAGEMENT SYSTEM")
    root.geometry('600x350')
    
    #=======frames====
    HR=Frame(root)
    Schain=Frame(root)
    
    #=========================functions for switching the frames========
    def change_to_HR():
        HR.pack(fill=BOTH, expand=1)
        Schain.pack_forget()
    
    def change_to_Schain():
        Schain.pack(fill=BOTH, expand=1)
        HR.pack_forget()
    
    #=====================Add heading logo in the frames======
    labelHR=Label(HR, text="HR DEPARTMENT")
    labelHR.pack(pady=20)
    
    labelSchain=Label(Schain, text="SUPPLY CHAIN DEPARTMENT")
    labelSchain.pack(pady=20)
    #===============================add button to switch between frames=====
    btn1=Button(root, text="HR", command=change_to_HR)
    btn1.pack(pady=20)
    btn2=Button(root, text="SUPPLY CHAIN", command=change_to_Schain)
    btn2.pack(pady=20)
    
    root.mainloop()