Aplicación Tkinter para cambiar entre diferentes marcos de página

Requisitos previos: interfaz gráfica de usuario de Python – tkinter
 

A veces sucede que necesitamos crear una aplicación con varios cuadros de diálogo emergentes, es decir, marcos de página. ¡Aquí hay un proceso paso a paso para crear múltiples marcos de página de Tkinter y vincularlos! Esto se puede usar como modelo para aplicaciones GUI de Python más complejas, como la creación de interfaces para laboratorios virtuales para experimentos, aulas, etc.
 

Aquí están los pasos: 

  • Crea tres páginas diferentes. Aquí tenemos tres páginas diferentes, la página de inicio como página de inicio, la página uno y la página dos. 
  • Cree un contenedor para cada marco de página. 
  • Tenemos cuatro clases. Primero está la clase tkinterApp, donde inicializamos los tres marcos y definimos una función show_frame que se llama cada vez que el usuario hace clic en un botón. 
  • La página de inicio es simple con dos botones para ir a la página 1 y la página 2. 
  • La página 1 tiene dos botones, uno para la página 2 y otro para volver a la página de inicio. 
  • La página 2 también tiene dos botones, uno para la página 1 y otros para volver a la página de inicio. 
  • Esta es una aplicación simplista de navegar entre marcos Tkinter. 
  • Esto se puede usar como modelo para aplicaciones más complejas y se pueden agregar varias funciones. 
     

La aplicación comienza con StartPage como la primera página, como se muestra en la clase tkinterApp. Aquí en StartApp, hay dos botones. Al hacer clic en un botón, se accede a la página respectiva. Puede agregar imágenes y gráficos a estas páginas y agregar funciones complejas. Las páginas también tienen dos botones. Cada vez que se presiona un botón, se llama a show_frame, que muestra la página respectiva.
A continuación se muestra la implementación.
 

Python3

import tkinter as tk
from tkinter import ttk
  
 
LARGEFONT =("Verdana", 35)
  
class tkinterApp(tk.Tk):
     
    # __init__ function for class tkinterApp
    def __init__(self, *args, **kwargs):
         
        # __init__ function for class Tk
        tk.Tk.__init__(self, *args, **kwargs)
         
        # creating a container
        container = tk.Frame(self) 
        container.pack(side = "top", fill = "both", expand = True)
  
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
  
        # initializing frames to an empty array
        self.frames = {} 
  
        # iterating through a tuple consisting
        # of the different page layouts
        for F in (StartPage, Page1, Page2):
  
            frame = F(container, self)
  
            # initializing frame of that object from
            # startpage, page1, page2 respectively with
            # for loop
            self.frames[F] = frame
  
            frame.grid(row = 0, column = 0, sticky ="nsew")
  
        self.show_frame(StartPage)
  
    # to display the current frame passed as
    # parameter
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
  
# first window frame startpage
  
class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
         
        # label of frame Layout 2
        label = ttk.Label(self, text ="Startpage", font = LARGEFONT)
         
        # putting the grid in its place by using
        # grid
        label.grid(row = 0, column = 4, padx = 10, pady = 10)
  
        button1 = ttk.Button(self, text ="Page 1",
        command = lambda : controller.show_frame(Page1))
     
        # putting the button in its place by
        # using grid
        button1.grid(row = 1, column = 1, padx = 10, pady = 10)
  
        ## button to show frame 2 with text layout2
        button2 = ttk.Button(self, text ="Page 2",
        command = lambda : controller.show_frame(Page2))
     
        # putting the button in its place by
        # using grid
        button2.grid(row = 2, column = 1, padx = 10, pady = 10)
  
          
  
  
# second window frame page1
class Page1(tk.Frame):
     
    def __init__(self, parent, controller):
         
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text ="Page 1", font = LARGEFONT)
        label.grid(row = 0, column = 4, padx = 10, pady = 10)
  
        # button to show frame 2 with text
        # layout2
        button1 = ttk.Button(self, text ="StartPage",
                            command = lambda : controller.show_frame(StartPage))
     
        # putting the button in its place
        # by using grid
        button1.grid(row = 1, column = 1, padx = 10, pady = 10)
  
        # button to show frame 2 with text
        # layout2
        button2 = ttk.Button(self, text ="Page 2",
                            command = lambda : controller.show_frame(Page2))
     
        # putting the button in its place by
        # using grid
        button2.grid(row = 2, column = 1, padx = 10, pady = 10)
  
  
  
  
# third window frame page2
class Page2(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text ="Page 2", font = LARGEFONT)
        label.grid(row = 0, column = 4, padx = 10, pady = 10)
  
        # button to show frame 2 with text
        # layout2
        button1 = ttk.Button(self, text ="Page 1",
                            command = lambda : controller.show_frame(Page1))
     
        # putting the button in its place by
        # using grid
        button1.grid(row = 1, column = 1, padx = 10, pady = 10)
  
        # button to show frame 3 with text
        # layout3
        button2 = ttk.Button(self, text ="Startpage",
                            command = lambda : controller.show_frame(StartPage))
     
        # putting the button in its place by
        # using grid
        button2.grid(row = 2, column = 1, padx = 10, pady = 10)
  
  
# Driver Code
app = tkinterApp()
app.mainloop()

Producción:

switch-between-different-page-frames-python-1

switch-between-different-page-frames-python-2

Publicación traducida automáticamente

Artículo escrito por soumibardhan10 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *