Home > database >  How to switch between two tkinter frames
How to switch between two tkinter frames

Time:04-15

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()

CodePudding user response:

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()

CodePudding user response:

This is here for comment archival only. Please see Sriram Srinivasan's answer if you're need an actual one.

Your indentation is off, starting with line 2. If you look again, you're defining change_to_Schain() inside of change_to_HR(), which makes it inaccessible to the main loop.

  • Related