From 1595f4325f86422c37760ad540871763fbf53c0a Mon Sep 17 00:00:00 2001 From: Juanjo Date: Tue, 12 Nov 2024 12:41:08 +0100 Subject: [PATCH] ejemplos de ventanas --- pruebas_ventanas/estructura.py | 85 +++++++++++++++++++++++++++++++++ pruebas_ventanas/mdi.py | 86 ++++++++++++++++++++++++++++++++++ pruebas_ventanas/solapas.py | 83 ++++++++++++++++++++++++++++++++ 3 files changed, 254 insertions(+) create mode 100644 pruebas_ventanas/estructura.py create mode 100644 pruebas_ventanas/mdi.py create mode 100644 pruebas_ventanas/solapas.py diff --git a/pruebas_ventanas/estructura.py b/pruebas_ventanas/estructura.py new file mode 100644 index 0000000..f4220aa --- /dev/null +++ b/pruebas_ventanas/estructura.py @@ -0,0 +1,85 @@ +import tkinter as tk +from tkinter import ttk +from tkinter import messagebox +import threading +import time +import datetime + +def update_time(status_bar): + """Función que actualiza la hora y el día de la semana en un label""" + while True: + # Obtener la fecha y hora actual + now = datetime.datetime.now() + day_of_week = now.strftime("%A") # Día de la semana + time_str = now.strftime("%H:%M:%S") # Hora en formato HH:MM:SS + date_str = now.strftime("%Y-%m-%d") # Fecha en formato YYYY-MM-DD + label_text = f"{day_of_week}, {date_str} - {time_str}" + + # Actualizar el label (debemos usar `after` para asegurarnos que se actualice en el hilo principal de Tkinter) + status_bar.after(1000, status_bar.config, {"text": label_text}) + + # Espera 1 segundo antes de actualizar de nuevo + time.sleep(1) + +def main(): + # Crear ventana principal + root = tk.Tk() + root.title("Aplicación con Menú y Layout") + root.geometry("1600x600") # Dimensiones de la ventana + + # Configuración del Menú Superior + menubar = tk.Menu(root, font=("Helvetica", 16)) + + # Menú "Archivo" + file_menu = tk.Menu(menubar, tearoff=0) + file_menu.add_command(label="Nuevo", command=lambda: messagebox.showinfo("Nuevo", "Nueva opción seleccionada")) + file_menu.add_command(label="Abrir", command=lambda: messagebox.showinfo("Abrir", "Abrir opción seleccionada")) + file_menu.add_separator() + file_menu.add_command(label="Salir", command=root.quit) + menubar.add_cascade(label="Archivo", menu=file_menu) + + # Menú "Editar" + edit_menu = tk.Menu(menubar, tearoff=0) + edit_menu.add_command(label="Copiar", command=lambda: messagebox.showinfo("Copiar", "Copiar opción seleccionada")) + edit_menu.add_command(label="Pegar", command=lambda: messagebox.showinfo("Pegar", "Pegar opción seleccionada")) + menubar.add_cascade(label="Editar", menu=edit_menu) + + # Menú "Ayuda" + help_menu = tk.Menu(menubar, tearoff=0) + help_menu.add_command(label="Acerca de", command=lambda: messagebox.showinfo("Acerca de", "Versión 1.0")) + menubar.add_cascade(label="Ayuda", menu=help_menu) + + # Configurar la barra de menú + root.config(menu=menubar) + + # Barra de estado + status_bar = tk.Label(root, text="Hilo fecha-hora", font=("Helvetica", 16), bd=1, fg="blue", relief="sunken", anchor="w") + status_bar.pack(side="bottom", fill="x",pady=2) + + # Frame lateral + sidebar_frame = tk.Frame(root, width=600, bg="lightgray") + sidebar_frame.pack(side="left", fill="y") + + # Frame principal + main_frame = tk.Frame(root, bg="white") + main_frame.pack(side="right", expand=True, fill="both") + + + + # Etiquetas de ejemplo en los Frames + sidebar_label = tk.Label(sidebar_frame, text="Panel Lateral", bg="lightgray") + sidebar_label.pack(padx=10, pady=10) + + main_label = tk.Label(main_frame, text="Panel Principal", bg="white") + main_label.pack(padx=10, pady=10) + + update_thread = threading.Thread(target=update_time, args=(status_bar,)) + update_thread.daemon = True # Hacemos el hilo un demonio para que termine con la app + update_thread.start() + + + # Ejecutar el bucle principal + root.mainloop() + +if __name__ == "__main__": + main() diff --git a/pruebas_ventanas/mdi.py b/pruebas_ventanas/mdi.py new file mode 100644 index 0000000..8e8718a --- /dev/null +++ b/pruebas_ventanas/mdi.py @@ -0,0 +1,86 @@ +import tkinter as tk +from tkinter import messagebox + +class MDIApplication(tk.Tk): + def __init__(self): + super().__init__() + self.title("Aplicación MDI con Tkinter") + self.geometry("800x600") + + # Contador para nombrar las ventanas hijas + self.child_count = 0 + + # Menú superior + self.create_menu() + + def create_menu(self): + # Crear barra de menú + menubar = tk.Menu(self) + + # Menú "Archivo" + file_menu = tk.Menu(menubar, tearoff=0) + file_menu.add_command(label="Nuevo Documento", command=self.open_new_document) + file_menu.add_separator() + file_menu.add_command(label="Salir", command=self.quit) + menubar.add_cascade(label="Archivo", menu=file_menu) + + # Menú "Ventana" para organizar ventanas + window_menu = tk.Menu(menubar, tearoff=0) + window_menu.add_command(label="Organizar en Cascada", command=self.cascade_windows) + window_menu.add_command(label="Organizar en Mosaico", command=self.tile_windows) + menubar.add_cascade(label="Ventana", menu=window_menu) + + # Configurar la barra de menú + self.config(menu=menubar) + + def open_new_document(self): + """Abrir una nueva ventana hija (documento)""" + self.child_count += 1 + child = tk.Toplevel(self) + child.title(f"Documento {self.child_count}") + child.geometry("400x300") + + # Permitir mover las ventanas hijas + child.transient(self) # Asegura que cada ventana es hija de la principal + child.protocol("WM_DELETE_WINDOW", lambda: self.close_document(child)) + + # Etiqueta de ejemplo dentro de cada ventana hija + label = tk.Label(child, text=f"Contenido del Documento {self.child_count}") + label.pack(expand=True, padx=20, pady=20) + + def close_document(self, window): + """Cerrar una ventana hija específica""" + if messagebox.askokcancel("Cerrar documento", "¿Estás seguro de que deseas cerrar este documento?"): + window.destroy() + + def cascade_windows(self): + """Organizar ventanas hijas en cascada""" + x_offset = 30 + y_offset = 30 + for idx, child in enumerate(self.winfo_children()): + if isinstance(child, tk.Toplevel): + child.geometry(f"400x300+{x_offset * idx}+{y_offset * idx}") + + def tile_windows(self): + """Organizar ventanas hijas en mosaico""" + children = [child for child in self.winfo_children() if isinstance(child, tk.Toplevel)] + if not children: + return + + num_children = len(children) + cols = int(num_children ** 0.5) # Número de columnas en la cuadrícula + rows = (num_children // cols) + (num_children % cols > 0) # Filas necesarias + + win_width = self.winfo_width() // cols + win_height = self.winfo_height() // rows + + for idx, child in enumerate(children): + row = idx // cols + col = idx % cols + x = col * win_width + y = row * win_height + child.geometry(f"{win_width}x{win_height}+{x}+{y}") + +if __name__ == "__main__": + app = MDIApplication() + app.mainloop() diff --git a/pruebas_ventanas/solapas.py b/pruebas_ventanas/solapas.py new file mode 100644 index 0000000..711d508 --- /dev/null +++ b/pruebas_ventanas/solapas.py @@ -0,0 +1,83 @@ +import tkinter as tk +from tkinter import ttk + +class Aplicacion(tk.Tk): + def __init__(self): + super().__init__() + + # Configuración de la ventana principal + self.title("Aplicación con Tkinter") + self.geometry("600x400") + + # Creación del menú superior + self.crear_menu() + + # Creación del frame de contenido central + self.crear_frame_central() + + # Creación de la barra de estado inferior + self.crear_barra_estado() + + def crear_menu(self): + # Barra de menú + menubar = tk.Menu(self) + + # Menú "Archivo" + archivo_menu = tk.Menu(menubar, tearoff=0) + archivo_menu.add_command(label="Nuevo") + archivo_menu.add_command(label="Abrir") + archivo_menu.add_command(label="Guardar") + archivo_menu.add_separator() + archivo_menu.add_command(label="Salir", command=self.quit) + menubar.add_cascade(label="Archivo", menu=archivo_menu) + + # Menú "Editar" + editar_menu = tk.Menu(menubar, tearoff=0) + editar_menu.add_command(label="Deshacer") + editar_menu.add_command(label="Rehacer") + menubar.add_cascade(label="Editar", menu=editar_menu) + + # Menú "Ayuda" + ayuda_menu = tk.Menu(menubar, tearoff=0) + ayuda_menu.add_command(label="Acerca de") + menubar.add_cascade(label="Ayuda", menu=ayuda_menu) + + # Asignar el menú a la ventana + self.config(menu=menubar) + + def crear_frame_central(self): + # Frame central con pestañas + frame_central = ttk.Frame(self) + frame_central.pack(fill="both", expand=True, padx=10, pady=10) + + # Notebook para las pestañas + notebook = ttk.Notebook(frame_central) + notebook.pack(fill="both", expand=True) + + # Crear cinco solapas + for i in range(1, 6): + tab = ttk.Frame(notebook) + notebook.add(tab, text=f"Solapa {i}") + # Añadir un Label en cada solapa para diferenciarla + label = ttk.Label(tab, text=f"Contenido de la Solapa {i}") + label.pack(pady=10) + + def crear_barra_estado(self): + # Barra de estado inferior con tres secciones + barra_estado = ttk.Frame(self, relief="sunken") + barra_estado.pack(side="bottom", fill="x") + + # Crear tres secciones en la barra de estado + seccion_izquierda = ttk.Label(barra_estado, text="Sección 1") + seccion_izquierda.pack(side="left", padx=10) + + seccion_centro = ttk.Label(barra_estado, text="Sección 2") + seccion_centro.pack(side="left", padx=10) + + seccion_derecha = ttk.Label(barra_estado, text="Sección 3") + seccion_derecha.pack(side="right", padx=10) + +# Crear y ejecutar la aplicación +if __name__ == "__main__": + app = Aplicacion() + app.mainloop()