ChatPersonas/Vista.py

145 lines
6.3 KiB
Python

import tkinter as tk
from tkinter import scrolledtext
from server import start_server
class VistaChat:
def __init__(self, root, controlador):
self.root = root
self.root.title("Chat Cliente-Servidor")
self.root.geometry("500x400") # Establece tamaño fijo
self.root.resizable(False, False) # Bloquea el redimensionamiento
self.root.configure(bg="#2C3E50")
self.controlador = controlador
# Estilos de los botones
btn_style = {"font": ("Arial", 10, "bold"), "fg": "white", "bg": "#2980B9", "bd": 0, "relief": "flat"}
# FRAME LATERAL PARA EL MENÚ
self.menu_frame = tk.Frame(root, width=100, bg="#34495E")
self.menu_frame.grid(row=0, column=0, rowspan=3, sticky="ns")
#self.button_inicio = tk.Button(self.menu_frame, text="Inicio", command=self.mostrar_inicio, width=12, **btn_style)
#self.button_inicio.pack(pady=10)
self.button_conf = tk.Button(self.menu_frame, text="Conf", command=self.mostrar_config, width=12, **btn_style)
self.button_conf.pack(pady=10)
# Almacenar botones de clientes conectados
self.chat_buttons = {}
self.chats_frames = {}
# FRAME PRINCIPAL DONDE SE MUESTRA EL CHAT O LA CONFIGURACIÓN
self.main_frame = tk.Frame(root, bg="#2C3E50")
self.main_frame.grid(row=0, column=1, padx=10, pady=10, rowspan=3)
# INICIALIZA LOS CHATS Y CONFIGURACIÓN
self.inicializar_config()
#self.inicializar_chat("127.0.0.1") # Chat local por defecto
#self.mostrar_chat("127.0.0.1")
def inicializar_chat(self, host):
"""Crea un nuevo chat con un host específico."""
chat_frame = tk.Frame(self.main_frame, bg="#2C3E50")
chat_display = scrolledtext.ScrolledText(chat_frame, wrap=tk.WORD, state='disabled', width=50, height=15, bg="#ECF0F1", fg="black")
chat_display.pack(padx=10, pady=10)
entry_frame = tk.Frame(chat_frame, bg="#2C3E50")
entry_frame.pack(pady=5)
message_entry = tk.Entry(entry_frame, width=40, font=("Arial", 10))
message_entry.pack(side=tk.LEFT, padx=10, pady=5)
send_button = tk.Button(entry_frame, text="Enviar", command=lambda: self.controlador.enviar_mensaje(host), state='disabled', font=("Arial", 10, "bold"), fg="white", bg="#27AE60", bd=0, relief="flat")
send_button.pack(side=tk.RIGHT, padx=5, pady=5)
self.chats_frames[host] = {
"frame": chat_frame,
"display": chat_display,
"entry": message_entry,
"send_button": send_button
}
def inicializar_config(self):
"""Configura la interfaz de configuración."""
self.config_frame = tk.Frame(self.main_frame, bg="#2C3E50")
tk.Label(self.config_frame, text="HOST:", bg="#2C3E50", fg="white", font=("Arial", 10, "bold")).pack(pady=2)
self.host_entry = tk.Entry(self.config_frame, width=20, font=("Arial", 10))
self.host_entry.pack(pady=5)
self.host_entry.insert(0, "127.0.0.1")
tk.Label(self.config_frame, text="PORT:", bg="#2C3E50", fg="white", font=("Arial", 10, "bold")).pack(pady=2)
self.port_entry = tk.Entry(self.config_frame, width=10, font=("Arial", 10))
self.port_entry.pack(pady=5)
self.port_entry.insert(0, "3333")
btn_style = {"font": ("Arial", 10, "bold"), "fg": "white", "bg": "#2980B9", "bd": 0, "relief": "flat"}
self.connect_button = tk.Button(self.config_frame, text="Conectar Cliente", command=self.controlador.conectar_cliente, **btn_style)
self.connect_button.pack(pady=10)
self.start_server = tk.Button(self.config_frame, text="Abrir servidor", command=self.controlador.iniciar_servidor, **btn_style)
self.start_server.pack(pady=20)
def mostrar_inicio(self):
"""Muestra la pantalla de chat predeterminado (127.0.0.1)."""
self.config_frame.pack_forget()
if "127.0.0.1" in self.chats_frames:
self.chats_frames["127.0.0.1"]["frame"].pack()
def mostrar_chat(self, host):
"""Muestra un chat específico y oculta los anteriores, incluyendo la configuración."""
# Ocultar la configuración si está visible
self.config_frame.pack_forget()
# Ocultar todos los chats antes de mostrar el nuevo
for chat_host, chat in self.chats_frames.items():
chat["frame"].pack_forget()
# Mostrar el chat seleccionado
if host in self.chats_frames:
self.chats_frames[host]["frame"].pack()
def mostrar_config(self):
"""Muestra la pantalla de configuración y oculta cualquier chat abierto."""
# Ocultar todos los chats
for chat in self.chats_frames.values():
chat["frame"].pack_forget()
# Mostrar la configuración
self.config_frame.pack()
def mostrar_mensaje(self, host, mensaje):
"""Muestra un mensaje en el chat correspondiente."""
if host in self.chats_frames:
chat_display = self.chats_frames[host]["display"]
chat_display.config(state='normal')
chat_display.insert(tk.END, mensaje + '\n')
chat_display.config(state='disabled')
chat_display.yview(tk.END)
def habilitar_envio(self, host):
"""Habilita el botón de enviar mensajes para el chat correspondiente."""
if host in self.chats_frames:
self.chats_frames[host]["send_button"].config(state='normal')
def deshabilitar_envio(self):
"""Deshabilita el botón de enviar mensajes."""
self.send_button.config(state='disabled')
def agregar_boton_chat(self, host):
"""Agrega un nuevo botón al menú lateral cuando se conecta un nuevo cliente."""
if host not in self.chat_buttons:
btn_style = {"font": ("Arial", 10, "bold"), "fg": "white", "bg": "#2980B9", "bd": 0, "relief": "flat"}
chat_button = tk.Button(self.menu_frame, text=f"Chat {host}", command=lambda: self.mostrar_chat(host), width=12, **btn_style)
chat_button.pack(pady=5)
self.chat_buttons[host] = chat_button
self.inicializar_chat(host)