Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple pages in Tkinter GUI (without opening new windows) using functions?

Tags:

tkinter

I want to create a GUI where there are several pages which I want to get open in the same window when their respective buttons are clicked. There is one solution using classes that I have come across: Using buttons in Tkinter to navigate to different pages of the application? However, I am new to Tkinter and the GUI I have implemented so far has been using functions and not classes. Can someone explain how to do this using functions?

like image 778
Shwetanshu Raj Avatar asked Oct 19 '25 00:10

Shwetanshu Raj


1 Answers

I guess here's what you want. Please try to include some code next time so that others can help more directly. The idea is to destroy all the widgets then build another page when the button is pressed. .winfo_children() returns all the children of "root"

import tkinter as tk

def page1(root):
    page = tk.Frame(root)
    page.grid()
    tk.Label(page, text = 'This is page 1').grid(row = 0)
    tk.Button(page, text = 'To page 2', command = changepage).grid(row = 1)

def page2(root):
    page = tk.Frame(root)
    page.grid()
    tk.Label(page, text = 'This is page 2').grid(row = 0)
    tk.Button(page, text = 'To page 1', command = changepage).grid(row = 1)

def changepage():
    global pagenum, root
    for widget in root.winfo_children():
        widget.destroy()
    if pagenum == 1:
        page2(root)
        pagenum = 2
    else:
        page1(root)
        pagenum = 1

pagenum = 1
root = tk.Tk()
page1(root)
root.mainloop()

I understand that object and class are a bit clumsy when we first learn about programming. But they are extremely useful when you get used to it.

like image 194
Mayan Avatar answered Oct 22 '25 08:10

Mayan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!