4

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?

  • 1
    If you have a working GUI and you need someone to review your code and provide pointers then you should ask this question on [Code Review](https://codereview.stackexchange.com). Be sure to include your full GUI their thought as they will need the code to actually review it. That said this question is not specific enough for Stack Overflow. – Mike - SMT Oct 08 '19 at 19:23

1 Answers1

7

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.

Mayan
  • 492
  • 4
  • 11