Funcionamineto de labels horizontales

This commit is contained in:
Andrés Moran 2024-12-08 02:16:04 +01:00
parent d205dc8395
commit 74654949e8
4 changed files with 229 additions and 164 deletions

Binary file not shown.

76
app/monitorization.py Normal file
View File

@ -0,0 +1,76 @@
from tkinter import messagebox
import threading
import time
import datetime
import psutil
def monitor_cpu_usage(label):
"""Monitorea y actualiza el uso de CPU en tiempo real."""
while True:
cpu_percent = psutil.cpu_percent(interval=1) # Obtiene el uso de CPU cada segundo
label.config(text=f"CPU: {cpu_percent}%")
time.sleep(1)
def monitor_ram_usage(label):
"""Monitorea y actualiza el uso de RAM en tiempo real."""
while True:
memory_info = psutil.virtual_memory()
ram_percent = memory_info.percent # Porcentaje de uso de RAM
label.config(text=f"RAM: {ram_percent}%")
time.sleep(1)
def monitor_battery(label):
"""Monitorea el estado de la batería y actualiza un label."""
low_battery_alert_shown = False # Bandera para evitar múltiples alertas
while True:
try:
# Obtiene la información de la batería
battery = psutil.sensors_battery()
if battery:
percent = battery.percent
charging = "Cargando" if battery.power_plugged else "Descargando"
# Validar el tiempo restante
if battery.secsleft == psutil.POWER_TIME_UNKNOWN or battery.secsleft < 0:
time_left_str = "Calculando..."
else:
hours = battery.secsleft // 3600
minutes = (battery.secsleft % 3600) // 60
time_left_str = f"{hours}h {minutes}m"
# Mostrar alerta si la batería es menor o igual al 15% y no está cargando
if percent <= 15 and not battery.power_plugged and not low_battery_alert_shown:
low_battery_alert_shown = True
label.after(0, lambda: messagebox.showwarning(
"Batería Baja",
"El nivel de batería está por debajo del 15%. Por favor, conecta el cargador."
))
# Resetear la bandera si se conecta el cargador
if battery.power_plugged:
low_battery_alert_shown = False
label.after(0, lambda: label.config(
text=f"Batería: {percent}% - {charging} - {time_left_str} restantes"
))
else:
# Si no hay batería, mostrar un mensaje
label.after(0, lambda: label.config(text="Batería: No disponible"))
except Exception as e:
label.after(0, lambda: label.config(text=f"Error: {str(e)[:30]}..."))
time.sleep(5) # Actualiza cada 5 segundos
def monitor_network_usage(label):
"""Monitorea y actualiza el uso de la red en tiempo real."""
prev_net = psutil.net_io_counters()
while True:
time.sleep(1) # Intervalo de actualización
current_net = psutil.net_io_counters()
sent = (current_net.bytes_sent - prev_net.bytes_sent) / (1024 * 1024) # En MB
recv = (current_net.bytes_recv - prev_net.bytes_recv) / (1024 * 1024) # En MB
prev_net = current_net
label.config(text=f"Red: Enviado {sent:.2f} MB, Recibido {recv:.2f} MB")

164
app/ui.py
View File

@ -1,164 +0,0 @@
import tkinter as tk
from tkinter import Menu # Importar el widget Menu
from tkinter import ttk # Importar el widget ttk
import threading
import time
import datetime
import psutil
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)
label_fecha_hora.after(1000, status_bar.config, {"text": label_text})
# Espera 1 segundo antes de actualizar de nuevo
time.sleep(1)
def monitor_cpu_usage(label):
"""Monitorea y actualiza el uso de CPU en tiempo real."""
while True:
cpu_percent = psutil.cpu_percent(interval=1) # Obtiene el uso de CPU cada segundo
label.config(text=f"CPU: {cpu_percent}%")
time.sleep(1)
def monitor_ram_usage(label):
"""Monitorea y actualiza el uso de RAM en tiempo real."""
while True:
memory_info = psutil.virtual_memory()
ram_percent = memory_info.percent # Porcentaje de uso de RAM
label.config(text=f"RAM: {ram_percent}%")
time.sleep(1)
# Crear la ventana principal
root = tk.Tk()
root.title("Ventana Responsive")
root.geometry("1000x700") # Tamaño inicial
# Configurar la ventana principal para que sea responsive
root.columnconfigure(0, weight=0) # Columna izquierda, tamaño fijo
root.columnconfigure(1, weight=1) # Columna central, tamaño variable
root.columnconfigure(2, weight=0) # Columna derecha, tamaño fijo
root.rowconfigure(0, weight=1) # Fila principal, tamaño variable
root.rowconfigure(1, weight=0) # Barra de estado, tamaño fijo
# Crear el menú superior
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Nuevo")
file_menu.add_command(label="Abrir")
file_menu.add_separator()
file_menu.add_command(label="Salir", command=root.quit)
edit_menu = Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Copiar")
edit_menu.add_command(label="Pegar")
help_menu = Menu(menu_bar, tearoff=0)
help_menu.add_command(label="Acerca de")
menu_bar.add_cascade(label="Archivo", menu=file_menu)
menu_bar.add_cascade(label="Editar", menu=edit_menu)
menu_bar.add_cascade(label="Ayuda", menu=help_menu)
root.config(menu=menu_bar)
# Crear los frames laterales y el central
frame_izquierdo = tk.Frame(root, bg="lightblue", width=200)
frame_central = tk.Frame(root, bg="white")
frame_derecho = tk.Frame(root, bg="lightgreen", width=200)
# Colocar los frames laterales y el central
frame_izquierdo.grid(row=0, column=0, sticky="ns")
frame_central.grid(row=0, column=1, sticky="nsew")
frame_derecho.grid(row=0, column=2, sticky="ns")
# Configurar los tamaños fijos de los frames laterales
frame_izquierdo.grid_propagate(False)
frame_derecho.grid_propagate(False)
# Dividir el frame central en dos partes (superior variable e inferior fija)
frame_central.rowconfigure(0, weight=1) # Parte superior, tamaño variable
frame_central.rowconfigure(1, weight=0) # Parte inferior, tamaño fijo
frame_central.columnconfigure(0, weight=1) # Ocupa toda la anchura
# Crear subframes dentro del frame central
frame_superior = tk.Frame(frame_central, bg="lightyellow")
frame_inferior = tk.Frame(frame_central, bg="lightgray", height=100)
# Colocar los subframes dentro del frame central
frame_superior.grid(row=0, column=0, sticky="nsew")
frame_inferior.grid(row=1, column=0, sticky="ew")
# Fijar el tamaño de la parte inferior
frame_inferior.grid_propagate(False)
# Crear la barra de estado
barra_estado = tk.Label(root, text="Barra de estado", bg="lightgray", anchor="w")
barra_estado.grid(row=1, column=0, columnspan=3, sticky="ew")
# Notebook para las pestañas
style = ttk.Style()
style.configure("CustomNotebook.TNotebook.Tab", font=("Arial", 12, "bold"))
notebook = ttk.Notebook(frame_superior, style="CustomNotebook.TNotebook")
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}", padding=4)
# Añadir un Label en cada solapa para diferenciarla
label = ttk.Label(tab, text=f"Contenido de la Solapa {i}")
label.pack(pady=10)
# Barra de estado
# Dividir la barra de estado en 4 labels
# Usar pack para alinear los labels horizontalmente
label_cpu_used = tk.Label(barra_estado, text="CPU: 0%", bg="green", anchor="w", width=20)
label_ram_used = tk.Label(barra_estado, text="RAM: 0%", bg="blue", anchor="w", width=20)
label_3 = tk.Label(barra_estado, text="Estado 3", bg="cyan", anchor="w", width=20)
label_4 = tk.Label(barra_estado, text="Estado 4", bg="pink", anchor="w", width=20)
label_fecha_hora = tk.Label(barra_estado, text="Hilo fecha-hora", font=("Helvetica", 14), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_cpu_used.pack(side="left", fill="x", expand=True)
label_ram_used.pack(side="left", fill="x", expand=True)
label_3.pack(side="left", fill="x", expand=True)
label_4.pack(side="left", fill="x", expand=True)
label_fecha_hora.pack(side="right", fill="x", expand=True)
# barra_estado.grid(row=1, column=0, columnspan=3, sticky="ew")
update_thread = threading.Thread(target=update_time, args=(label_fecha_hora,))
update_thread.daemon = True # Hacemos el hilo un demonio para que termine con la app
update_thread.start()
# Iniciar el hilo para actualizar el uso de CPU
thread_cpu_monitor = threading.Thread(target=monitor_cpu_usage, args=(label_cpu_used,))
thread_cpu_monitor.daemon = True # Aseguramos que el hilo termine con la app
thread_cpu_monitor.start()
thread_ram_monitor = threading.Thread(target=monitor_ram_usage, args=(label_ram_used,))
thread_ram_monitor.daemon = True
thread_ram_monitor.start()
# Ejecución de la aplicación
root.mainloop()

153
main.py
View File

@ -0,0 +1,153 @@
import tkinter as tk
from tkinter import Menu # Importar el widget Menu
from tkinter import ttk # Importar el widget ttk
from tkinter import messagebox
from app import monitorization
import threading
import time
import datetime
import psutil
def update_time(status_bar):
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)
label_fecha_hora.after(1000, status_bar.config, {"text": label_text})
# Espera 1 segundo antes de actualizar de nuevo
time.sleep(1)
# Crear la ventana principal
root = tk.Tk()
root.title("Ventana Responsive")
root.geometry("1000x700") # Tamaño inicial
# Configurar la ventana principal para que sea responsive
root.columnconfigure(0, weight=0) # Columna izquierda, tamaño fijo
root.columnconfigure(1, weight=1) # Columna central, tamaño variable
root.columnconfigure(2, weight=0) # Columna derecha, tamaño fijo
root.rowconfigure(0, weight=1) # Fila principal, tamaño variable
root.rowconfigure(1, weight=0) # Barra de estado, tamaño fijo
# Crear el menú superior
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Nuevo")
file_menu.add_command(label="Abrir")
file_menu.add_separator()
file_menu.add_command(label="Salir", command=root.quit)
edit_menu = Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Copiar")
edit_menu.add_command(label="Pegar")
help_menu = Menu(menu_bar, tearoff=0)
help_menu.add_command(label="Acerca de")
menu_bar.add_cascade(label="Archivo", menu=file_menu)
menu_bar.add_cascade(label="Editar", menu=edit_menu)
menu_bar.add_cascade(label="Ayuda", menu=help_menu)
root.config(menu=menu_bar)
# Crear los frames laterales y el central
frame_izquierdo = tk.Frame(root, bg="lightblue", width=200)
frame_central = tk.Frame(root, bg="white")
frame_derecho = tk.Frame(root, bg="lightgreen", width=200)
# Colocar los frames laterales y el central
frame_izquierdo.grid(row=0, column=0, sticky="ns")
frame_central.grid(row=0, column=1, sticky="nsew")
frame_derecho.grid(row=0, column=2, sticky="ns")
# Configurar los tamaños fijos de los frames laterales
frame_izquierdo.grid_propagate(False)
frame_derecho.grid_propagate(False)
# Dividir el frame central en dos partes (superior variable e inferior fija)
frame_central.rowconfigure(0, weight=1) # Parte superior, tamaño variable
frame_central.rowconfigure(1, weight=0) # Parte inferior, tamaño fijo
frame_central.columnconfigure(0, weight=1) # Ocupa toda la anchura
# Crear subframes dentro del frame central
frame_superior = tk.Frame(frame_central, bg="lightyellow")
frame_inferior = tk.Frame(frame_central, bg="lightgray", height=100)
# Colocar los subframes dentro del frame central
frame_superior.grid(row=0, column=0, sticky="nsew")
frame_inferior.grid(row=1, column=0, sticky="ew")
# Fijar el tamaño de la parte inferior
frame_inferior.grid_propagate(False)
# Crear la barra de estado
barra_estado = tk.Label(root, text="Barra de estado", bg="lightgray", anchor="w")
barra_estado.grid(row=1, column=0, columnspan=3, sticky="ew")
# Notebook para las pestañas
style = ttk.Style()
style.configure("CustomNotebook.TNotebook.Tab", font=("Arial", 12, "bold"))
notebook = ttk.Notebook(frame_superior, style="CustomNotebook.TNotebook")
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}", padding=4)
# Añadir un Label en cada solapa para diferenciarla
label = ttk.Label(tab, text=f"Contenido de la Solapa {i}")
label.pack(pady=10)
# Barra de estado
# Dividir la barra de estado en 4 labels
# Usar pack para alinear los labels horizontalmente
label_cpu_used = tk.Label(barra_estado, text="CPU: 0%", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_ram_used = tk.Label(barra_estado, text="RAM: 0%", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_pc_battery = tk.Label(barra_estado, text="Temperatura CPU: ", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_network_used = tk.Label(barra_estado, text="Red: ", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_fecha_hora = tk.Label(barra_estado, text="Hilo fecha-hora", font=("Helvetica", 11), bd=1, fg="blue", relief="sunken", anchor="w", width=20, padx=10)
label_cpu_used.pack(side="left", fill="x", expand=True)
label_ram_used.pack(side="left", fill="x", expand=True)
label_pc_battery.pack(side="left", fill="x", expand=True)
label_network_used.pack(side="left", fill="x", expand=True)
label_fecha_hora.pack(side="right", fill="x", expand=True)
update_thread = threading.Thread(target=update_time, args=(label_fecha_hora,))
update_thread.daemon = True
update_thread.start()
thread_cpu_monitor = threading.Thread(target=monitorization.monitor_cpu_usage, args=(label_cpu_used,))
thread_cpu_monitor.daemon = True
thread_cpu_monitor.start()
thread_ram_monitor = threading.Thread(target=monitorization.monitor_ram_usage, args=(label_ram_used,))
thread_ram_monitor.daemon = True
thread_ram_monitor.start()
thread_temperature_battery = threading.Thread(target=monitorization.monitor_battery, args=(label_pc_battery,))
thread_temperature_battery.daemon = True
thread_temperature_battery.start()
thread_network_used_monitor = threading.Thread(target=monitorization.monitor_network_usage, args=(label_network_used,))
thread_network_used_monitor.daemon = True
thread_network_used_monitor.start()
# Ejecución de la aplicación
root.mainloop()