Compare commits

...

4 Commits

Author SHA1 Message Date
c0b6b881e4 Add chat project 2024-01-25 22:26:39 +01:00
bd197dc519 Add calculator project 2024-01-24 18:45:39 +01:00
81e279e30a Add notepad project 2024-01-24 18:45:08 +01:00
23805c8241 Add library exercises 2024-01-24 18:44:22 +01:00
7 changed files with 482 additions and 0 deletions

View File

@ -2,6 +2,8 @@
"""
Librería tkinter - messagebox
Con dir(messagebox) podemos ver los métodos que tiene esta librería
"""
import tkinter as tk

View File

@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""
Editor de texto simple
"""
import tkinter as tk
from tkinter import filedialog, messagebox
class SimpleTextEditor:
def __init__(self, root):
self.root = root
self.text_area = tk.Text(self.root)
self.text_area.pack(expand=True, fill=tk.BOTH)
self.current_open_file = ""
def new_file(self):
self.text_area.delete("1.0", tk.END)
self.current_open_file = ""
def open_file(self):
filename = filedialog.askopenfilename(
title="Seleccione un archivo"
)
if filename:
self.text_area.delete("1.0", tk.END)
with open(filename, 'r') as file:
self.text_area.insert("1.0", file.read())
self.current_open_file = filename
def save_file(self):
if not self.current_open_file:
new_file_path = filedialog.asksaveasfilename(
title="Guardar archivo"
)
if new_file_path:
self.current_open_file = new_file_path
else:
return
with open(self.current_open_file, 'w') as file:
file.write(self.text_area.get("1.0", tk.END))
def quit_confirm(self):
if messagebox.askokcancel("Salir", "¿Está seguro que desea salir?"):
self.root.destroy()
root = tk.Tk()
root.geometry("900x700")
root.title("Editor de texto simple")
editor = SimpleTextEditor(root)
menu_bar = tk.Menu(root)
menu_options = tk.Menu(menu_bar, tearoff=0)
menu_options.add_command(label="Nuevo", command=editor.new_file)
menu_options.add_command(label="Abrir", command=editor.open_file)
menu_options.add_command(label="Guardar", command=editor.save_file)
menu_options.add_command(label="Salir", command=editor.quit_confirm)
root.config(menu=menu_bar)
menu_bar.add_cascade(label="Archivo", menu=menu_options)
root.mainloop()

View File

@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""
Calculadora
"""
import tkinter as tk
class Calculadora:
"""
Clase calculadora
"""
def __init__(self, master):
self.master = master
self.display = tk.Entry(
master, width=20, font=("Arial", 23), justify="right",
bd=10, insertwidth=1, bg="#6495DE"
)
self.display.grid(row=0, column=0, columnspan=4)
self.op_verification = False
self.current = ''
self.op = ''
self.total = 0
row = 1
col = 0
buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", ".", "+",
"="
]
for button in buttons:
self.build_button(button, row, col)
col += 1
if col > 3:
col = 0
row += 1
if row == 5:
col += 2
self.master.bind("<Key>", self.key_press)
def key_press(self, event):
key = event.char
if key in "0123456789.+-*/":
self.click(key)
elif key == "\r":
self.calculate()
elif key == "\x08":
self.clear_display()
elif key == "\x1b":
self.master.quit()
return
else:
print(f"\n[+] Tecla presionada: {key}")
print(f"[+] Valor actual: {self.current}")
print(f"[+] Verificación de operador: {self.op_verification}")
print(f"[+] Operador: {self.op}")
print(f"[+] Total: {self.total}")
def clear_display(self):
self.display.delete(0, tk.END)
self.op_verification = False
self.current = ''
self.op = ''
self.total = 0
def calculate(self):
if self.current and self.op:
if self.op == "+":
self.total += float(self.current)
elif self.op == "-":
self.total -= float(self.current)
elif self.op == "*":
self.total *= float(self.current)
elif self.op == "/":
self.total /= float(self.current)
self.display.delete(0, "end")
self.display.insert(tk.END, round(self.total, 3))
return self.total
def click(self, key):
if self.op_verification:
self.op_verification = False
self.display.insert(tk.END, key)
if key in "0123456789" or key == ".":
self.current += key
else:
if self.current:
if not self.op:
self.total = float(self.current)
self.current = ''
self.op_verification = True
self.op = key
print(f"\n[+] Tecla presionada: {key}")
print(f"[+] Valor actual: {self.current}")
print(f"[+] Verificación de operador: {self.op_verification}")
print(f"[+] Operador: {self.op}")
print(f"[+] Total: {self.total}")
def build_button(self, button, row, col):
if button == "C":
b = tk.Button(
self.master, text=button,
width=3,
font=("Arial", 23),
command=lambda: self.clear_display()
)
elif button == "=":
b = tk.Button(
self.master, text=button,
width=8, height=2,
font=("Arial", 23),
command=lambda: self.calculate()
)
else:
b = tk.Button(
self.master, text=button,
width=3,
font=("Arial", 23),
command=lambda: self.click(button)
)
b.grid(row=row, column=col, columnspan=2 if row == 5 else 1)
root = tk.Tk()
root.title("Calculadora")
root.resizable(width=False, height=False)
my_gui = Calculadora(root)
root.mainloop()

View File

@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""
CLIENTE DE CHAT CIFRADO E2E
"""
import socket as s
import threading as th
from tkinter import *
from tkinter.scrolledtext import ScrolledText
def send_message(client_socket, username, text_widget, entry_widget):
local_address = client_socket.getsockname()
ip_address, port = local_address
message = entry_widget.get()
client_socket.sendall(
f'{username} ({ip_address}:{port}): {message}\n'.encode())
entry_widget.delete(0, END)
text_widget.configure(state='normal')
text_widget.insert(END, f'{username} ({ip_address}:{port}): {message}\n')
text_widget.configure(state='disabled')
def receive_message(client_socket, text_widget):
while True:
try:
message = client_socket.recv(1024).decode()
if not message:
break
text_widget.configure(state='normal')
text_widget.insert(END, message)
text_widget.configure(state='disabled')
except:
break
def list_users_request(client_socket):
client_socket.sendall("!usuarios".encode())
def exit_request(client_socket, username, window):
client_socket.sendall(
f"\n[!] El usuario {username} ha abandonado el chat\n".encode()
)
client_socket.close()
window.quit()
window.destroy()
def client_program():
host = 'localhost'
port = 1234
client_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
client_socket.connect((host, port))
username = input("\n[+] Introduce tu usuario: ")
if not username:
username = "Anonymus"
client_socket.sendall(username.encode())
window = Tk()
window.title(f'Chat cifrado E2E - {username}')
# window.geometry('500x700')
# window.iconbitmap("oveja-negra.ico")
# window.iconphoto(False, PhotoImage(file="oveja-negra.png"))
text_widget = ScrolledText(window, state='disabled')
text_widget.pack(padx=5, pady=5)
frame_widget = Frame(window)
frame_widget.pack(fill=BOTH, expand=True, padx=5, pady=5)
entry_widget = Entry(frame_widget, font=('Arial', 12))
entry_widget.bind(
"<Return>",
lambda _: send_message(
client_socket, username,
text_widget, entry_widget
)
)
entry_widget.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)
button_widget = Button(
frame_widget, text="Enviar",
command=lambda: send_message(
client_socket, username,
text_widget, entry_widget
)
)
button_widget.pack(side=RIGHT, padx=5, pady=5)
users_widget = Button(
window, text="Listar usuarios",
command=lambda: list_users_request(client_socket))
users_widget.pack(padx=5, pady=5)
exit_widget = Button(
window, text="Salir",
command=lambda: exit_request(client_socket, username, window))
exit_widget.pack(padx=5, pady=5)
thread = th.Thread(
target=receive_message,
args=(client_socket, text_widget)
)
thread.daemon = True
thread.start()
window.mainloop()
client_socket.close()
if __name__ == '__main__':
client_program()

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

View File

@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""
SERVER DE CHAT CIFRADO E2E
"""
import socket as s
import threading as th
def client_thread(client_socket, clients, usernames):
username = client_socket.recv(1024).decode()
usernames[client_socket] = username
print(f"\n[+] El usuario {username} se ha conectado al chat")
for client in clients:
if client is not client_socket:
client.sendall(
f"\n[+] El usuario {username} se ha conectado al chat\n\n".encode()
)
while True:
try:
message = client_socket.recv(1024).decode()
if not message:
break
if message == "!usuarios":
client_socket.sendall(
f"\n[i] Usuarios conectados: {', '.join(usernames.values())}\n\n".encode()
)
continue
for client in clients:
if client is not client_socket:
client.sendall(message.encode())
except:
break
client_socket.close()
clients.remove(client_socket)
del usernames[client_socket]
def server_program():
host = 'localhost'
port = 1234
server_socket = s.socket(s.AF_INET, s.SOCK_STREAM)
server_socket.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1) # TIME_WAIT
server_socket.bind((host, port))
server_socket.listen()
print(f"\n[+] Server está en escucha...")
clients = []
usernames = {}
while True:
client_socket, addr = server_socket.accept()
clients.append(client_socket)
print(f"\n[+] Conectado a {addr}")
thread = th.Thread(
target=client_thread,
args=(client_socket, clients, usernames)
)
thread.daemon = True
thread.start()
server_socket.close()
if __name__ == '__main__':
server_program()