How to move between windows?

Asked

Viewed 44 times

-3

I’m creating a simple system just to learn a little bit about the Tkinter library. However, I stopped right here.

The idea is to create several pages in the same code (I know that the correct one would modularize the code, but because it is a small project, everything together will serve). However, I would like to be able to press a button and thus travel from one page to another.

For example, I run the program and then I am shown Page 1.

When clicking the "Page 2" button, I should go to page 2. Where there should be a "Back" button that takes me back to Page 1.

And this process should take place with any page that I want to create. I want to ask for this help because all the codes I found were very confusing and/or did not work with separate pages where the button would call them.

Code:

from tkinter import *
import sys

janela1 = Tk()
b1 = Button(janela1, text="Janela 2")
b1.grid()
b2 = Button(janela1, text="Janela 3")
b2.grid()
janela1.geometry("200x100")
janela1.mainloop()

sys.exit()

janela2 = Tk()
b3 = Button(janela2, text="Voltar")
b3.grid()
janela2.geometry("200x100")
janela2.mainloop()

janela3 = Tk()
b4 = Button(janela3, text="Voltar")
b4.grid()
janela3.geometry("200x100")
janela3.mainloop()
  • Are "windows" or "pages"?

  • I think it doesn’t change much. I call window in code, but page for client.

1 answer

2


For that there is the Tkinter.Frame and with the method pack to display the frame you want and using the pack_forget (can use the forget_grid if working with grids) to hide (remove), very simple example:

from tkinter import *

root = Tk()

frame1 = Frame(root)
frame2 = Frame(root)


def go_home():
    frame2.pack_forget()
    frame1.pack()


def go_second():
    frame1.pack_forget()
    frame2.pack()


root.title("páginas")

btn_page2 = Button(frame1, text="Página 2", command=go_second)
btn_page2.pack()

btn_home = Button(frame2, text="inicial", command=go_home)
btn_home.pack()

frame1.pack()

root.mainloop()

There is also the method raise which has the python equivalent as frame.tkraise(), which will change the order of the frames added to root, in which case both frames will always be there (in which case I have not found documented in Python, so I find I will try to produce an example).

  • Attributeerror: '_Tkinter.tkapp' Object has no attribute 'pack_forget' E is my impression, or in this your code, everything is in one page, so you keep hiding and releasing elements?

  • I understand your method, and even though it’s not exactly what I wanted, I think it will work perfectly for what I want. Thank you, William.

  • @Ivifernando are different frames, that would be equivalent to pages, now if you want different windows, there is something else.

  • I noticed this. Your solution was perfect for my case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.