├── Codigo ├── Anexo Python │ ├── HolaMundo.py │ ├── clases.py │ ├── diccionarios.py │ ├── ejemploDepuracion.py │ ├── entrada_usuario.py │ ├── ficheros.py │ ├── funciones.py │ ├── funciones_lambda.py │ ├── gestion clientes │ │ ├── __pycache__ │ │ │ ├── clases.cpython-37.pyc │ │ │ └── gestion_clientes.cpython-37.pyc │ │ ├── clases.py │ │ ├── clientes.pkl │ │ └── gestion_clientes.py │ ├── listas.py │ ├── miModulo.py │ ├── modulos.py │ ├── sentenciasControl.py │ ├── threads.py │ └── variables.py └── Tkinter │ ├── eventos │ ├── eventos_editor grafico.py │ ├── eventos_editor_texto.py │ └── eventos_tamanio_ventana.py │ ├── gestion clientes │ ├── __pycache__ │ │ ├── clases.cpython-37.pyc │ │ └── gestion_clientes.cpython-37.pyc │ ├── clases.py │ ├── clientes.pkl │ ├── gestion_clientes.py │ └── interfaz_gestion_clientes.py │ ├── hellow_world.py │ ├── imagenes │ ├── abrir_archivo.gif │ ├── anadir_pestana.gif │ ├── borrar_pestana.gif │ ├── guardar_archivo.gif │ ├── pelota.gif │ └── salir.gif │ ├── metodos comunes │ ├── metodos_comunes_foco.py │ ├── metodos_comunes_posicion_raton.py │ └── metodos_comunes_temporizadores.py │ ├── opciones comunes │ ├── lista_fuentes.py │ ├── opciones_comunes1.py │ ├── opciones_comunes2.py │ ├── opciones_comunes3.py │ ├── opciones_comunes4.py │ └── opciones_comunes5.py │ ├── posicionamiento y dise¤o │ ├── grid_1.py │ ├── grid_2.py │ ├── pack.py │ └── place.py │ ├── ttk │ ├── archivo_texto.txt │ ├── archivo_texto2.txt │ ├── ttk_checkbutton_radiobutton.py │ ├── ttk_combobox.py │ ├── ttk_estilos.py │ ├── ttk_mapa_estados.py │ ├── ttk_notebook.py │ ├── ttk_progressbar.py │ ├── ttk_separator.py │ └── ttk_sizegrip.py │ ├── validacion entrada de datos │ └── validacion_entrada_datos.py │ ├── variables de control │ └── variables_control.py │ ├── ventana principal │ └── ventana_principal.py │ └── widgets │ ├── archivo_texto.html │ ├── archivo_texto.txt │ ├── archivo_texto2.txt │ ├── button.py │ ├── canvas_arc.py │ ├── canvas_circulo.py │ ├── canvas_imagen.py │ ├── canvas_lineas.py │ ├── canvas_poligono.py │ ├── canvas_rectangulo.py │ ├── canvas_text.py │ ├── checkbutton_editor_texto.py │ ├── checkbutton_radiobutton_formulario.py │ ├── colorchooser.py │ ├── entry.py │ ├── frames.py │ ├── label_reloj.py │ ├── listbox.py │ ├── menu.py │ ├── menubutton.py │ ├── messagebox.py │ ├── optionmenu.py │ ├── panedwindow.py │ ├── scale_arco.py │ ├── scroll.py │ ├── spinbox.py │ ├── text.py │ └── toplevel.py └── README.md /Codigo/Anexo Python/HolaMundo.py: -------------------------------------------------------------------------------- 1 | print("Hola Mundo") 2 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/clases.py: -------------------------------------------------------------------------------- 1 | class Perro: 2 | def __init__(self, nombre, raza): 3 | self.nombre = nombre 4 | self.raza = raza 5 | 6 | def ladrar(self): 7 | print("¡Guau!") 8 | 9 | class Persona: 10 | def __init__(self, nombre, dni): 11 | self.nombre = nombre 12 | self.dni = dni 13 | 14 | def mostrarAtributos(self): 15 | print("Nombre de la persona: " + self.nombre) 16 | print("DNI: " + str(self.dni)) 17 | 18 | class Cliente(Persona): 19 | def __init__(self, nombre, dni, perro): 20 | Persona.__init__(self, nombre, dni) 21 | self.perro = perro 22 | def mostrarAtributos(self): 23 | super().mostrarAtributos() 24 | print("Nombre del perro: " + self.perro.nombre) 25 | print("Raza: " + self.perro.raza) 26 | 27 | mi_perro = Perro("Snooy", "Beagle") 28 | yo = Cliente("Tomás", 1234, mi_perro) 29 | yo.mostrarAtributos() 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/diccionarios.py: -------------------------------------------------------------------------------- 1 | yo = { 2 | "nombre" : "Tomás", 3 | "NIF" : 1234567, 4 | "dirección" : "Madrid" 5 | } 6 | 7 | mi_perro = { 8 | "nombre": "Snoppy", 9 | "raza": "Beagle", 10 | "sexo": "macho", 11 | "edad": 10, 12 | "dueño": yo 13 | } 14 | 15 | print("---DATOS DEL PERRO---") 16 | for clave_perro, valor_perro in mi_perro.items(): 17 | if clave_perro == "dueño" : 18 | print("---DATOS DEL DUEÑO---") 19 | for clave_dueño, valor_dueño in valor_perro.items(): 20 | print(clave_dueño + ":" + str(valor_dueño)) 21 | else : print(clave_perro + ":" + str(valor_perro)) 22 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/ejemploDepuracion.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | numero1 = randint(1, 10) 4 | numero2 = randint(1, 10) 5 | numero = numero1 + numero2 6 | 7 | respuesta = int(input("Cuánto es " + str(numero1) + " + " + str(numero2) + "? ")) 8 | 9 | if respuesta == numero: 10 | print("¡Correcto!") 11 | else: 12 | print("No es correcto, la respuesta es " + str(numero)) 13 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/entrada_usuario.py: -------------------------------------------------------------------------------- 1 | nombre = input("¿Cómo te llamas? ") 2 | print("Encantado de conocerte, " + nombre) 3 | 4 | 5 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/ficheros.py: -------------------------------------------------------------------------------- 1 | FICHERO = "miFichero.txt" 2 | empresa1 = {"nombre":"Empresa1", "direccion":"Suiza", "facturacion":1000} 3 | empresa2 = {"nombre":"Empresa2", "direccion":"Irlanda", "facturacion":2000} 4 | lista_empresas = [empresa1, empresa2] 5 | 6 | def mostrar_datos_empresas(lista_empresas): 7 | for empresa in lista_empresas: 8 | for clave, valor in empresa.items(): 9 | print(clave + ":" + str(valor)) 10 | print("---") 11 | 12 | print("Se procede a guardar los datos de las siguientes empresas") 13 | mostrar_datos_empresas(lista_empresas) 14 | 15 | with open(FICHERO, "w") as f: 16 | for empresa in lista_empresas: 17 | for clave, valor in empresa.items(): 18 | f.write(clave + ":" + str(valor) + "#") 19 | f.write("\n") 20 | 21 | lista_empresas_cargadas = [] 22 | f = open(FICHERO, "r") 23 | for linea in f: 24 | empresa = {} 25 | lista_pares_clave_valor = linea.split("#") 26 | lista_pares_clave_valor.pop() 27 | for clave_valor in lista_pares_clave_valor: 28 | lista_clave_valor = clave_valor.split(":") 29 | clave = lista_clave_valor[0] 30 | valor = lista_clave_valor[1] 31 | empresa[clave] = valor 32 | lista_empresas_cargadas.append(empresa) 33 | 34 | print("Se han leído los datos de la siguientes empresas") 35 | mostrar_datos_empresas(lista_empresas_cargadas) 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/funciones.py: -------------------------------------------------------------------------------- 1 | def datos(nombre, direccion, telefono): 2 | if nombre == "" : print("No tengo tu nombre") 3 | else : print("Hola " + nombre) 4 | if direccion != "" : print("Vives en "+direccion) 5 | else : print("No tengo tu dirección") 6 | if telefono != "" : print("Tu teléfono es "+telefono) 7 | else : print("No tengo tu teléfono") 8 | 9 | nombre = input("¿Cómo te llamas? ") 10 | direccion = input("¿Cuál es tu dirección? ") 11 | telefono = input("¿Cuál es tu número de teléfono? ") 12 | 13 | datos(telefono=telefono, nombre=nombre, direccion=direccion) 14 | 15 | ##def hola(nombre = ""): 16 | ## if nombre == "" : print("Hola") 17 | ## else : print("Hola " + nombre) 18 | ## 19 | ##hola() 20 | ##nombre = input("¿Cómo te llamas? ") 21 | ##hola(nombre) 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/funciones_lambda.py: -------------------------------------------------------------------------------- 1 | def escalar(numero): 2 | return lambda multiplicador : multiplicador * numero 3 | 4 | doblar = escalar(2) 5 | triplicar = escalar(3) 6 | 7 | numero = int(input("Escriba un número: ")) 8 | 9 | numero_doblado = doblar(numero) 10 | numero_triplicado = triplicar(numero) 11 | 12 | print("El doble de "+str(numero)+ " es "+str(numero_doblado)) 13 | print("El triple de "+str(numero)+ " es "+str(numero_triplicado)) 14 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/gestion clientes/__pycache__/clases.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Anexo Python/gestion clientes/__pycache__/clases.cpython-37.pyc -------------------------------------------------------------------------------- /Codigo/Anexo Python/gestion clientes/__pycache__/gestion_clientes.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Anexo Python/gestion clientes/__pycache__/gestion_clientes.cpython-37.pyc -------------------------------------------------------------------------------- /Codigo/Anexo Python/gestion clientes/clases.py: -------------------------------------------------------------------------------- 1 | class Perro: 2 | def __init__(self, nombre, raza): 3 | self.nombre = nombre 4 | self.raza = raza 5 | 6 | def ladrar(self): 7 | print("¡Guau!") 8 | 9 | class Persona: 10 | def __init__(self, nombre, dni): 11 | self.nombre = nombre 12 | self.dni = dni 13 | 14 | def mostrarAtributos(self): 15 | print(self.nombre + "\t" + str(self.dni), end="\t") 16 | 17 | class Cliente(Persona): 18 | def __init__(self, nombre, dni, perro): 19 | Persona.__init__(self, nombre, dni) 20 | self.perro = perro 21 | def mostrarAtributos(self): 22 | super().mostrarAtributos() 23 | print(self.perro.nombre + "\t" + self.perro.raza) 24 | 25 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/gestion clientes/clientes.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Anexo Python/gestion clientes/clientes.pkl -------------------------------------------------------------------------------- /Codigo/Anexo Python/gestion clientes/gestion_clientes.py: -------------------------------------------------------------------------------- 1 | import clases 2 | import os 3 | import pickle 4 | from tabulate import tabulate 5 | 6 | fichero_clientes = "clientes.pkl" 7 | datos_modificados = False 8 | lista_clientes = [] 9 | if os.path.exists(fichero_clientes): 10 | with open(fichero_clientes, 'rb') as f: 11 | lista_clientes = pickle.load(f) 12 | 13 | 14 | def mostrar_opciones(): 15 | print("\n") 16 | print("1- Alta") 17 | print("2- Baja") 18 | print("3- Modificación") 19 | print("4- Consultar cliente") 20 | print("5- Consulta global") 21 | print("6- Salvar") 22 | print("7- Salir") 23 | opcion = input("Elija una opción: ") 24 | print("\n") 25 | return opcion 26 | 27 | def datos_cliente(dni): 28 | for cliente in lista_clientes: 29 | if cliente.dni == dni: return cliente 30 | return None 31 | 32 | def alta(): 33 | global datos_modificados 34 | print("Por favor, introduzca el valor de los siguientes campos") 35 | dni = input("DNI: ") 36 | if datos_cliente(dni) == None: 37 | nombre_cliente = input("Nombre del cliente: ") 38 | nombre_perro = input("Nombre del perro: ") 39 | raza = input("Raza: ") 40 | 41 | perro = clases.Perro(nombre_perro, raza) 42 | cliente = clases.Cliente(nombre_cliente, dni, perro) 43 | 44 | lista_clientes.append(cliente) 45 | print("---Cliente dado de alta---") 46 | datos_modificados = True 47 | else: print("---Ya existe un cliente con el DNI " + dni + "---") 48 | 49 | def modificacion(): 50 | global datos_modificados 51 | dni = input("DNI del cliente a modificar: ") 52 | cliente = datos_cliente(dni) 53 | if cliente == None: print("---El cliente con DNI " + dni + " no existe---") 54 | else: 55 | print("Por favor, rellene los siguientes campos") 56 | nombre_cliente = input("Nombre del cliente: ") 57 | if nombre_cliente != "": cliente.nombre = nombre_cliente 58 | nombre_perro = input("Nombre del perro: ") 59 | if nombre_perro != "":cliente.perro.nombre = nombre_perro 60 | raza = input("Raza: ") 61 | if raza != "":cliente.perro.raza = raza 62 | print("---Cliente modificado---") 63 | datos_modificados = True 64 | 65 | def baja(): 66 | global datos_modificados 67 | dni = input("DNI del cliente a dar de baja: ") 68 | cliente = datos_cliente(dni) 69 | if cliente == None: print("---El cliente con DNI " + dni + " no existe---") 70 | else: 71 | lista_clientes.remove(cliente) 72 | print("---Cliente borrado---") 73 | datos_modificados = True 74 | 75 | def consulta_cliente(): 76 | dni = input("DNI del cliente a consultar: ") 77 | cliente = datos_cliente(dni) 78 | if cliente == None: print("---El cliente con DNI " + dni + " no existe---") 79 | else: 80 | tabla = [[cliente.nombre, cliente.dni, cliente.perro.nombre, cliente.perro.raza]] 81 | tabla_con_formato = tabulate(tabla, ["Cliente", "DNI", "Perro", "Raza"]) 82 | print(tabla_con_formato) 83 | 84 | def consulta_global(): 85 | tabla = [] 86 | for cliente in lista_clientes: 87 | fila = [cliente.nombre, cliente.dni, cliente.perro.nombre, cliente.perro.raza] 88 | tabla.append(fila) 89 | tabla_con_formato = tabulate(tabla, ["Cliente", "DNI", "Perro", "Raza"]) 90 | print(tabla_con_formato) 91 | 92 | def salvar(): 93 | with open(fichero_clientes, 'wb') as f: 94 | pickle.dump(lista_clientes, f) 95 | print("---Información de cliente guardada---") 96 | datos_modificados = False 97 | 98 | while True: 99 | opcion = mostrar_opciones() 100 | if opcion == "1": alta() 101 | elif opcion == "2": baja() 102 | elif opcion == "3": modificacion() 103 | elif opcion == "4": consulta_cliente() 104 | elif opcion == "5": consulta_global() 105 | elif opcion == "6": salvar() 106 | elif opcion == "7": 107 | if datos_modificados : 108 | respuesta = input("¿Quiere guardar los cambios realizados?(s/n) ") 109 | if respuesta == "s" : salvar() 110 | break 111 | else:print("---Opción no válida---") 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/listas.py: -------------------------------------------------------------------------------- 1 | lista1 = [1, 2] 2 | lista2 = [] 3 | 4 | lista2 = lista1.copy() 5 | 6 | lista2.append(3) 7 | 8 | print("elementos de lista1: " + str(lista1)) 9 | print("elementos de lista2: " + str(lista2)) 10 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/miModulo.py: -------------------------------------------------------------------------------- 1 | variable = "Soy la variable de miModulo.py" 2 | 3 | def funcion(): 4 | print("Soy la función de miModulo.py") 5 | 6 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/modulos.py: -------------------------------------------------------------------------------- 1 | from tabulate import tabulate 2 | 3 | cabecera = ["NOMBRE", "DIRECCIÓN", "TELÉFONO"] 4 | datos_persona1 = ["Tomás", "Gran Vía, 10, 1ºA", "9112345"] 5 | datos_persona2 = ["Juan", "Alcalá, 11, 2ºB", "9167890"] 6 | 7 | tabla =[datos_persona1, datos_persona2] 8 | tabla_con_formato = tabulate(tabla, cabecera) 9 | print(tabla_con_formato) 10 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/sentenciasControl.py: -------------------------------------------------------------------------------- 1 | edad = 9 2 | marca = "Mercedes" 3 | 4 | if (edad < 10) and (marca == "BMW" or marca == "Mercedes"): 5 | print("Te compro el " + marca + " de " + str(edad) + " años") 6 | else: 7 | print("No compro ese tipo de coches") 8 | 9 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/threads.py: -------------------------------------------------------------------------------- 1 | import time, threading 2 | 3 | segundos = 0 4 | 5 | def interrumpir(): 6 | while True: 7 | time.sleep(2) 8 | print("INTERRUMPO") 9 | 10 | hilo = threading.Thread(target=interrumpir) 11 | hilo.start() 12 | 13 | while True: 14 | print(segundos) 15 | segundos += 1 16 | time.sleep(1) 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Codigo/Anexo Python/variables.py: -------------------------------------------------------------------------------- 1 | nombre = "Tomás" 2 | hora = 12 3 | 4 | print("¿{} tiene cita a las {}?".format(nombre, hora)) 5 | -------------------------------------------------------------------------------- /Codigo/Tkinter/eventos/eventos_editor grafico.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas, Menu, colorchooser 2 | 3 | ancho_canvas = 600 4 | alto_canvas = 300 5 | 6 | objeto_pulsado = False 7 | dimension_objeto = 50 8 | posicion_x_previa = posicion_y_previa = 0 9 | 10 | #--------------------------------------------------------------------- 11 | #------------------------- MENÚS CONTEXTUALES ------------------------ 12 | #--------------------------------------------------------------------- 13 | 14 | def mostrar_popup_canvas(evento): 15 | global objeto_pulsado 16 | 17 | x = evento.x 18 | y = evento.y 19 | if not(objeto_pulsado) and x-dimension_objeto > 0 and x+dimension_objeto < ancho_canvas and y-dimension_objeto > 0 and y+dimension_objeto < alto_canvas: 20 | menu_canvas = Menu(tearoff=0) 21 | menu_canvas.add_command(label="Cuadrado", command=lambda:crear_cuadrado(x, y)) 22 | menu_canvas.add_command(label="Círculo", command=lambda:crear_circulo(x, y)) 23 | menu_canvas.add_command(label="Triángulo", command=lambda:crear_triangulo(x, y)) 24 | menu_canvas.post(evento.x_root, evento.y_root) 25 | 26 | objeto_pulsado = False 27 | 28 | def mostrar_popup_objeto(evento): 29 | global objeto_pulsado 30 | objeto_pulsado = True 31 | 32 | id = canvas.find_withtag('current')[0] 33 | 34 | menu_objeto = Menu(tearoff=0) 35 | menu_objeto.add_command(label="Color", command=lambda:pintar(id)) 36 | menu_objeto.add_command(label="Traer al frente", command=lambda:enviar_al_frente(id)) 37 | menu_objeto.add_command(label="Enviar al fondo", command=lambda:enviar_al_fondo(id)) 38 | menu_objeto.add_command(label="Borrar", command=lambda:borrar(id)) 39 | menu_objeto.post(evento.x_root, evento.y_root) 40 | 41 | #--------------------------------------------------------------------- 42 | #------------------------- OPCIONES DE MENÚS ------------------------- 43 | #--------------------------------------------------------------------- 44 | 45 | def crear_cuadrado(x, y): 46 | id = canvas.create_rectangle(x-dimension_objeto, y-dimension_objeto, x+dimension_objeto, y+dimension_objeto, fill="white") 47 | canvas.tag_bind(id, "", mostrar_popup_objeto) 48 | 49 | def crear_circulo(x, y): 50 | id = canvas.create_oval(x-dimension_objeto, y-dimension_objeto, x+dimension_objeto, y+dimension_objeto, fill="white") 51 | canvas.tag_bind(id, "", mostrar_popup_objeto) 52 | 53 | def crear_triangulo(x, y): 54 | puntos = [x, y-dimension_objeto, x+dimension_objeto, y+dimension_objeto, x-dimension_objeto, y+dimension_objeto] 55 | id = canvas.create_polygon(puntos, fill="white", outline="black") 56 | canvas.tag_bind(id, "", mostrar_popup_objeto) 57 | 58 | def pintar(id): 59 | color = colorchooser.askcolor(title ="Elige un color") 60 | if color: 61 | canvas.itemconfigure(id, fill=color[1], outline=color[1]) 62 | 63 | def enviar_al_frente(id): 64 | canvas.tag_raise(id) 65 | 66 | def enviar_al_fondo(id): 67 | canvas.tag_lower(id) 68 | 69 | def borrar(id): 70 | canvas.delete(id) 71 | 72 | #--------------------------------------------------------------------- 73 | #------------------ MOVIMIENTO DE OBJETOS GRÁFICOS ------------------- 74 | #--------------------------------------------------------------------- 75 | 76 | def iniciar_movimiento(evento): 77 | global posicion_x_previa, posicion_y_previa 78 | 79 | posicion_x_previa = evento.x 80 | posicion_y_previa = evento.y 81 | 82 | def mover_objeto(evento): 83 | global posicion_x_previa, posicion_y_previa 84 | 85 | lista_id = canvas.find_withtag('current') 86 | if lista_id != (): 87 | incremento_x = evento.x - posicion_x_previa 88 | incremento_y = evento.y - posicion_y_previa 89 | id= lista_id[0] 90 | esquinas = canvas.bbox(id) #(x1, y1, x2, y2) 91 | if esquinas[0]+incremento_x > 0 and esquinas[2]+incremento_x < ancho_canvas and esquinas[1]+incremento_y > 0 and esquinas[3]+incremento_y < alto_canvas: 92 | canvas.move(id, incremento_x, incremento_y) 93 | posicion_x_previa = evento.x 94 | posicion_y_previa = evento.y 95 | #--------------------------------------------------------------------- 96 | #------------------------- VENTANA PRINCIPAL ------------------------- 97 | #--------------------------------------------------------------------- 98 | 99 | root = Tk() 100 | root.resizable(False, False) 101 | root.title("Editor gráfico") 102 | canvas = Canvas(width = ancho_canvas, height = alto_canvas) 103 | canvas.pack() 104 | 105 | canvas.bind("", mostrar_popup_canvas) 106 | canvas.bind("", iniciar_movimiento) 107 | canvas.bind("", mover_objeto) 108 | 109 | root.mainloop() 110 | -------------------------------------------------------------------------------- /Codigo/Tkinter/eventos/eventos_editor_texto.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Menu, Text, filedialog, Scrollbar, messagebox 2 | 3 | fichero="" 4 | 5 | ########################################################## 6 | #Funciones que se ejecutan seleccionar una opción del menú 7 | ########################################################## 8 | 9 | def nuevo(): 10 | global fichero 11 | 12 | area_texto.delete(1.0, "end") 13 | fichero = "" 14 | 15 | def abrir(): 16 | global fichero 17 | 18 | fichero = filedialog.askopenfilename(initialdir = ".", title = "Abrir archivo", filetypes = [("ficheros texto", "*.txt")]) 19 | if fichero: 20 | f = open(fichero, "r", encoding='utf-8') 21 | area_texto.delete(1.0, "end") 22 | area_texto.insert("insert", f.read()) 23 | f.close() 24 | 25 | def guardar(): 26 | global fichero 27 | if not(fichero): fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 28 | if fichero: 29 | texto = area_texto.get(1.0, "end") 30 | f = open(fichero, "w", encoding='utf-8') 31 | f.write(texto) 32 | f.close 33 | 34 | def guardar_como(): 35 | global fichero 36 | 37 | fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar como", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 38 | if fichero: 39 | texto = area_texto.get(1.0, "end") 40 | f = open(fichero, "w", encoding='utf-8') 41 | f.write(texto) 42 | f.close 43 | 44 | def salir(): 45 | root.destroy() 46 | 47 | def cerrar_ventana(): 48 | if messagebox.askokcancel("Salir", "¿Desea realmente salir?"): 49 | root.destroy() 50 | 51 | def eventos_menu(evento): 52 | opcion = evento.char 53 | if opcion == "a":abrir() 54 | elif opcion == "g":guardar() 55 | elif opcion == "s":salir() 56 | 57 | #Ventana principal 58 | root = Tk() 59 | root.title("Editor de texto") 60 | 61 | #Creación de widgets de la ventana principal 62 | barra_menus = Menu() 63 | area_texto = Text(padx=10, pady=10, bd=5) 64 | scrollbar = Scrollbar(command=area_texto.yview) 65 | area_texto.config(yscrollcommand = scrollbar.set) 66 | 67 | #Menú Archivo 68 | menu_archivo = Menu(tearoff=0) 69 | menu_archivo.add_command(label="Nuevo", command=nuevo) 70 | 71 | submenu_abrir = Menu(tearoff=0) 72 | submenu_abrir.add_command(label="Archivo", command=abrir, accelerator="Alt-a") 73 | submenu_abrir.add_command(label="Recientes") 74 | menu_archivo.add_cascade(label='Abrir', menu=submenu_abrir) 75 | 76 | menu_archivo.add_command(label="Guardar", command=guardar, accelerator="Alt-g") 77 | menu_archivo.add_command(label="Guardar como", command=guardar_como) 78 | menu_archivo.add_separator() 79 | menu_archivo.add_command(label="Salir", command=salir, accelerator="Alt-s") 80 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 81 | 82 | #Menú edición 83 | menu_edicion = Menu(tearoff=0) 84 | menu_edicion.add_command(label="Deshacer") 85 | menu_edicion.add_command(label="Rehacer") 86 | menu_edicion.add_separator() 87 | menu_edicion.add_command(label="Copiar") 88 | menu_edicion.add_command(label="Pegar") 89 | menu_edicion.add_command(label="Borrar") 90 | menu_edicion.add_command(label="Seleccionar todo") 91 | barra_menus.add_cascade(label="Edición", menu=menu_edicion) 92 | 93 | #Menú ayuda 94 | menu_ayuda = Menu(tearoff=0) 95 | menu_ayuda.add_command(label="Manual de usuario") 96 | menu_ayuda.add_command(label="About...") 97 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 98 | 99 | #Composición de los widgets de la ventana principal 100 | root.config(menu=barra_menus) 101 | area_texto.pack(expand=True, fill="both", side = "left") 102 | scrollbar.pack(side = "right", fill = "y") 103 | 104 | root.bind("", eventos_menu) 105 | 106 | root.protocol("WM_DELETE_WINDOW", cerrar_ventana) 107 | 108 | root.mainloop() 109 | 110 | -------------------------------------------------------------------------------- /Codigo/Tkinter/eventos/eventos_tamanio_ventana.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas, PhotoImage 2 | from random import randint 3 | 4 | radio = 20 5 | ancho = 400 6 | alto = 200 7 | desplazamiento_x = 1 8 | desplazamiento_y = 1 9 | intervalo = 2 10 | 11 | centro_x = randint(radio, ancho) 12 | centro_y = randint(radio, alto) 13 | 14 | def redimensiona(evento): 15 | global ancho, alto 16 | 17 | ancho = evento.width 18 | alto = evento.height 19 | 20 | def mueve_pelota(): 21 | global desplazamiento_x, desplazamiento_y 22 | 23 | x, y = canvas.coords(pelota) 24 | root.minsize(int(x)+radio+1, int(y)+radio+1) 25 | if x-radio <= 0 or x+radio >= ancho: desplazamiento_x = -desplazamiento_x 26 | if y-radio <= 0 or y+radio >= alto: desplazamiento_y = -desplazamiento_y 27 | canvas.move(pelota, desplazamiento_x, desplazamiento_y) 28 | root.after(intervalo, mueve_pelota) 29 | 30 | root = Tk() 31 | canvas = Canvas(width = ancho, height = alto, bg="white") 32 | canvas.pack(fill="both", expand=True) 33 | 34 | img = PhotoImage(file="../imagenes/pelota.gif") 35 | pelota = canvas.create_image(centro_x, centro_y, image=img) 36 | 37 | root.bind("", redimensiona) 38 | 39 | mueve_pelota() 40 | 41 | root.mainloop() 42 | -------------------------------------------------------------------------------- /Codigo/Tkinter/gestion clientes/__pycache__/clases.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/gestion clientes/__pycache__/clases.cpython-37.pyc -------------------------------------------------------------------------------- /Codigo/Tkinter/gestion clientes/__pycache__/gestion_clientes.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/gestion clientes/__pycache__/gestion_clientes.cpython-37.pyc -------------------------------------------------------------------------------- /Codigo/Tkinter/gestion clientes/clases.py: -------------------------------------------------------------------------------- 1 | class Perro: 2 | def __init__(self, nombre, raza): 3 | self.nombre = nombre 4 | self.raza = raza 5 | 6 | def ladrar(self): 7 | print("¡Guau!") 8 | 9 | class Persona: 10 | def __init__(self, nombre, dni): 11 | self.nombre = nombre 12 | self.dni = dni 13 | 14 | def mostrarAtributos(self): 15 | print(self.nombre + "\t" + str(self.dni), end="\t") 16 | 17 | class Cliente(Persona): 18 | def __init__(self, nombre, dni, perro): 19 | Persona.__init__(self, nombre, dni) 20 | self.perro = perro 21 | def mostrarAtributos(self): 22 | super().mostrarAtributos() 23 | print(self.perro.nombre + "\t" + self.perro.raza) 24 | 25 | -------------------------------------------------------------------------------- /Codigo/Tkinter/gestion clientes/clientes.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/gestion clientes/clientes.pkl -------------------------------------------------------------------------------- /Codigo/Tkinter/gestion clientes/gestion_clientes.py: -------------------------------------------------------------------------------- 1 | import clases 2 | import os 3 | import pickle 4 | from tabulate import tabulate 5 | 6 | fichero_clientes = "clientes.pkl" 7 | lista_clientes = [] 8 | if os.path.exists(fichero_clientes): 9 | with open(fichero_clientes, 'rb') as f: 10 | lista_clientes = pickle.load(f) 11 | 12 | def obtener_cliente(dni): 13 | for cliente in lista_clientes: 14 | if cliente.dni == dni: return cliente 15 | return None 16 | 17 | def alta_cliente(dni, nombre_cliente, nombre_perro, raza): 18 | perro = clases.Perro(nombre_perro, raza) 19 | cliente = clases.Cliente(nombre_cliente, dni, perro) 20 | 21 | lista_clientes.append(cliente) 22 | print("---Cliente dado de alta---") 23 | 24 | def modificacion_cliente(cliente, nombre_cliente, nombre_perro, raza): 25 | cliente.nombre = nombre_cliente 26 | cliente.perro.nombre = nombre_perro 27 | cliente.perro.raza = raza 28 | print("---Cliente modificado---") 29 | 30 | def baja_cliente(cliente): 31 | lista_clientes.remove(cliente) 32 | print("---Cliente borrado---") 33 | 34 | def informacion_cliente(cliente): 35 | tabla = [[cliente.nombre, cliente.dni, cliente.perro.nombre, cliente.perro.raza]] 36 | tabla_con_formato = tabulate(tabla, ["Cliente", "DNI", "Perro", "Raza"]) 37 | return tabla_con_formato 38 | 39 | def informacion_clientes(): 40 | tabla = [] 41 | for cliente in lista_clientes: 42 | fila = [cliente.nombre, cliente.dni, cliente.perro.nombre, cliente.perro.raza] 43 | tabla.append(fila) 44 | tabla_con_formato = tabulate(tabla, ["Cliente", "DNI", "Perro", "Raza"]) 45 | return tabla_con_formato 46 | 47 | def guardar(): 48 | with open(fichero_clientes, 'wb') as f: 49 | pickle.dump(lista_clientes, f) 50 | print("---Información de cliente guardada---") 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /Codigo/Tkinter/gestion clientes/interfaz_gestion_clientes.py: -------------------------------------------------------------------------------- 1 | from gestion_clientes import * 2 | from tkinter import Tk, Label, Entry, Button, Menu, Text, PhotoImage, Scrollbar, messagebox, Toplevel 3 | 4 | datos_modificados = False 5 | 6 | def mostrar_resultado_operacion(mensaje): 7 | area_texto.configure(state="normal") 8 | area_texto.delete(1.0, "end") 9 | area_texto.insert(1.0, mensaje) 10 | area_texto.configure(state="disabled") 11 | 12 | #--------------------------------------------------------------------- 13 | #-------------------- FUNCIONES GESTIÓN DE BOTONES -------------------- 14 | #--------------------------------------------------------------------- 15 | 16 | def aceptar_alta(): 17 | global datos_modificados 18 | 19 | dni = dni_entry.get() 20 | nombre_cliente = nombre_cliente_entry.get() 21 | nombre_perro = nombre_perro_entry.get() 22 | raza = raza_entry.get() 23 | cliente = obtener_cliente(dni) 24 | 25 | if cliente != None: 26 | dni_entry.delete(0, "end") 27 | dni_entry.focus() 28 | else: 29 | alta_cliente(dni, nombre_cliente, nombre_perro, raza) 30 | datos_modificados = True 31 | ventana_auxiliar.destroy() 32 | cliente = obtener_cliente(dni) 33 | tabla_cliente = informacion_cliente(cliente) 34 | mostrar_resultado_operacion("Cliente dado de alta correctamente\n\n"+tabla_cliente) 35 | 36 | def aceptar_baja(): 37 | global datos_modificados 38 | 39 | dni = dni_entry.get() 40 | cliente = obtener_cliente(dni) 41 | if cliente == None: 42 | dni_entry.delete(0, "end") 43 | dni_entry.focus() 44 | else: 45 | baja_cliente(cliente) 46 | datos_modificados = True 47 | ventana_auxiliar.destroy() 48 | mostrar_resultado_operacion("Cliente dado de baja correctamente") 49 | 50 | def aceptar_modificacion(): 51 | global datos_modificados 52 | 53 | dni = dni_entry.get() 54 | nombre_cliente = nombre_cliente_entry.get() 55 | nombre_perro = nombre_perro_entry.get() 56 | raza = raza_entry.get() 57 | 58 | cliente = obtener_cliente(dni) 59 | modificacion_cliente(cliente, nombre_cliente, nombre_perro, raza) 60 | 61 | datos_modificados = True 62 | ventana_auxiliar.destroy() 63 | tabla_cliente = informacion_cliente(cliente) 64 | mostrar_resultado_operacion("Cliente modificado correctamente\n\n"+tabla_cliente) 65 | 66 | def aceptar_dni_modificacion(): 67 | global nombre_cliente_entry, nombre_perro_entry, raza_entry 68 | 69 | dni = dni_entry.get() 70 | cliente = obtener_cliente(dni) 71 | if cliente == None: 72 | dni_entry.delete(0, "end") 73 | dni_entry.focus() 74 | else: 75 | dni_entry.configure(state="disabled") 76 | 77 | nombre_cliente_label = Label(ventana_auxiliar, text="Nombre cliente:") 78 | nombre_cliente_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 79 | nombre_perro_label = Label(ventana_auxiliar, text="Nombre perro:") 80 | nombre_perro_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 81 | raza_label = Label(ventana_auxiliar, text="Raza:") 82 | raza_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 83 | 84 | nombre_cliente_entry.insert(0, cliente.nombre) 85 | nombre_perro_entry.insert(0, cliente.perro.nombre) 86 | raza_entry.insert(0, cliente.perro.raza) 87 | 88 | boton_aceptar.configure(command=aceptar_modificacion) 89 | 90 | nombre_cliente_label.grid(row=2, column=1, sticky= "W", padx=10, pady=10) 91 | nombre_cliente_entry.grid(row=2, column=2, padx=10) 92 | nombre_perro_label.grid(row=3, column=1, sticky= "W", padx=10, pady=10) 93 | nombre_perro_entry.grid(row=3, column=2, padx=10) 94 | raza_label.grid(row=4, column=1, sticky= "W", padx=10, pady=10) 95 | raza_entry.grid(row=4, column=2, padx=10) 96 | boton_aceptar.grid(row=5, column=1, padx=10, pady=10, sticky= "W") 97 | boton_cancelar.grid(row=5, column=2, padx=10, pady=10, sticky= "E") 98 | 99 | def aceptar_consulta_cliente(): 100 | dni = dni_entry.get() 101 | cliente = obtener_cliente(dni) 102 | if cliente == None: 103 | dni_entry.delete(0, "end") 104 | dni_entry.focus() 105 | else: 106 | tabla_cliente = informacion_cliente(cliente) 107 | mostrar_resultado_operacion(tabla_cliente) 108 | ventana_auxiliar.destroy() 109 | 110 | def cancelar(): 111 | ventana_auxiliar.destroy() 112 | 113 | #--------------------------------------------------------------------- 114 | #-------------------- FUNCIONES GESTIÓN DE OPCIONES ------------------- 115 | #--------------------------------------------------------------------- 116 | 117 | def alta(): 118 | global ventana_auxiliar, dni_entry, nombre_cliente_entry, nombre_perro_entry, raza_entry 119 | 120 | ventana_auxiliar = Toplevel() 121 | ventana_auxiliar.title("Alta cliente") 122 | ventana_auxiliar.resizable(False, False) 123 | 124 | dni_label = Label(ventana_auxiliar, text="DNI:") 125 | dni_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 126 | nombre_cliente_label = Label(ventana_auxiliar, text="Nombre cliente:") 127 | nombre_cliente_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 128 | nombre_perro_label = Label(ventana_auxiliar, text="Nombre perro:") 129 | nombre_perro_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 130 | raza_label = Label(ventana_auxiliar, text="Raza:") 131 | raza_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 132 | boton_aceptar = Button(ventana_auxiliar, text="ACEPTAR", command=aceptar_alta) 133 | boton_cancelar = Button(ventana_auxiliar, text="CANCELAR", command=cancelar) 134 | 135 | dni_label.grid(row=1, column=1, sticky= "W", padx=10, pady=10) 136 | dni_entry.grid(row=1, column=2, padx=10) 137 | nombre_cliente_label.grid(row=2, column=1, sticky= "W", padx=10, pady=10) 138 | nombre_cliente_entry.grid(row=2, column=2, padx=10) 139 | nombre_perro_label.grid(row=3, column=1, sticky= "W", padx=10, pady=10) 140 | nombre_perro_entry.grid(row=3, column=2, padx=10) 141 | raza_label.grid(row=4, column=1, sticky= "W", padx=10, pady=10) 142 | raza_entry.grid(row=4, column=2, padx=10) 143 | boton_aceptar.grid(row=5, column=1, padx=10, pady=10, sticky= "W") 144 | boton_cancelar.grid(row=5, column=2, padx=10, pady=10, sticky= "E") 145 | 146 | def baja(): 147 | global ventana_auxiliar, dni_entry 148 | 149 | ventana_auxiliar = Toplevel() 150 | ventana_auxiliar.title("Baja cliente") 151 | ventana_auxiliar.resizable(False, False) 152 | 153 | dni_label = Label(ventana_auxiliar, text="DNI:") 154 | dni_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 155 | boton_aceptar = Button(ventana_auxiliar, text="ACEPTAR", command=aceptar_baja) 156 | boton_cancelar = Button(ventana_auxiliar, text="CANCELAR", command=cancelar) 157 | 158 | dni_label.grid(row=1, column=1, sticky= "W", padx=10, pady=10) 159 | dni_entry.grid(row=1, column=2, padx=10) 160 | boton_aceptar.grid(row=2, column=1, padx=10, pady=10, sticky= "W") 161 | boton_cancelar.grid(row=2, column=2, padx=10, pady=10, sticky= "E") 162 | 163 | def modificacion(): 164 | global ventana_auxiliar, dni_entry, boton_aceptar, boton_cancelar 165 | 166 | ventana_auxiliar = Toplevel() 167 | ventana_auxiliar.title("Modificación cliente") 168 | ventana_auxiliar.resizable(False, False) 169 | 170 | dni_label = Label(ventana_auxiliar, text="DNI:") 171 | dni_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 172 | boton_aceptar = Button(ventana_auxiliar, text="ACEPTAR", command=aceptar_dni_modificacion) 173 | boton_cancelar = Button(ventana_auxiliar, text="CANCELAR", command=cancelar) 174 | 175 | dni_label.grid(row=1, column=1, sticky= "W", padx=10, pady=10) 176 | dni_entry.grid(row=1, column=2, padx=10) 177 | boton_aceptar.grid(row=2, column=1, padx=10, pady=10, sticky= "W") 178 | boton_cancelar.grid(row=2, column=2, padx=10, pady=10, sticky= "E") 179 | 180 | def consulta_cliente(): 181 | global ventana_auxiliar, dni_entry 182 | 183 | ventana_auxiliar = Toplevel() 184 | ventana_auxiliar.title("Consulta cliente") 185 | ventana_auxiliar.resizable(False, False) 186 | 187 | dni_label = Label(ventana_auxiliar, text="DNI:") 188 | dni_entry = Entry(ventana_auxiliar, bd=5, highlightcolor="red", highlightthickness=2) 189 | boton_aceptar = Button(ventana_auxiliar, text="ACEPTAR", command=aceptar_consulta_cliente) 190 | boton_cancelar = Button(ventana_auxiliar, text="CANCELAR", command=cancelar) 191 | 192 | dni_label.grid(row=1, column=1, sticky= "W", padx=10, pady=10) 193 | dni_entry.grid(row=1, column=2, padx=10) 194 | boton_aceptar.grid(row=2, column=1, padx=10, pady=10, sticky= "W") 195 | boton_cancelar.grid(row=2, column=2, padx=10, pady=10, sticky= "E") 196 | 197 | def consulta_clientes(): 198 | tabla_clientes = informacion_clientes() 199 | mostrar_resultado_operacion(tabla_clientes) 200 | 201 | def guardar_clientes(): 202 | global datos_modificados 203 | 204 | guardar() 205 | mostrar_resultado_operacion("Clientes almacenados correctamente") 206 | datos_modificados = False 207 | 208 | def salir(): 209 | if datos_modificados: 210 | if messagebox.askyesno("Salir", "¿Desea guardar los cambios antes de salir?"): 211 | guardar() 212 | root.destroy() 213 | 214 | def manual_usuario(): 215 | messagebox.showinfo("Manual de usuario", "En construcción...") 216 | 217 | def acerca_de(): 218 | messagebox.showinfo("Acerca de...", "Versión 1.0") 219 | 220 | #--------------------------------------------------------------------- 221 | #-------------------- FUNCIONES GESTIÓN DE EVENTOS ------------------- 222 | #--------------------------------------------------------------------- 223 | 224 | def eventos_menu(evento): 225 | tecla = evento.char 226 | if tecla == "a":alta() 227 | elif tecla == "b":baja() 228 | elif tecla == "m":modificacion() 229 | 230 | #--------------------------------------------------------------------- 231 | #------------------------- VENTANA PRINCIPAL ------------------------- 232 | #--------------------------------------------------------------------- 233 | 234 | root = Tk() 235 | root.title("Gestión de clientes") 236 | root.minsize(400, 200) 237 | 238 | barra_menus = Menu() 239 | root.config(menu=barra_menus) 240 | area_texto = Text(state="disabled", padx=10, pady=10, bd=5) 241 | scrollbar = Scrollbar(command=area_texto.yview) 242 | area_texto.config(yscrollcommand = scrollbar.set) 243 | 244 | menu_archivo = Menu(tearoff=0) 245 | menu_archivo.add_command(label="Guardar", command=guardar_clientes) 246 | menu_archivo.add_separator() 247 | img = PhotoImage(file="../imagenes/salir.gif") 248 | menu_archivo.add_command(label="Salir", image=img, compound="left", command=salir) 249 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 250 | 251 | menu_operaciones = Menu(tearoff=0) 252 | menu_operaciones.add_command(label="Alta", accelerator="Alt-a", command=alta) 253 | menu_operaciones.add_command(label="Baja", accelerator="Alt-b", command=baja) 254 | menu_operaciones.add_command(label="Modificación", accelerator="Alt-m", command=modificacion) 255 | menu_operaciones.add_separator() 256 | menu_operaciones.add_command(label="Consulta cliente", command=consulta_cliente) 257 | menu_operaciones.add_command(label="Consulta global", command=consulta_clientes) 258 | barra_menus.add_cascade(label="Operaciones", menu=menu_operaciones) 259 | 260 | menu_ayuda = Menu(tearoff=0) 261 | menu_ayuda.add_command(label="Manual de usuario", command=manual_usuario) 262 | menu_ayuda.add_command(label="Acerca de...", command=acerca_de) 263 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 264 | 265 | area_texto.pack(expand=True, fill="both", side = "left") 266 | scrollbar.pack(side = "right", fill = "y") 267 | 268 | root.bind("", eventos_menu) 269 | 270 | root.protocol("WM_DELETE_WINDOW", salir) 271 | 272 | root.mainloop() 273 | 274 | -------------------------------------------------------------------------------- /Codigo/Tkinter/hellow_world.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | root = Tk() 4 | 5 | etiqueta = Label(text="\n ¡Hola Mundo! \n") 6 | etiqueta.pack() 7 | 8 | 9 | ##class Interfaz: 10 | ## def __init__(self): 11 | ## self.etiqueta = Label(text="\n ¡Hola Mundo! \n") 12 | ## self.etiqueta.pack() 13 | ## 14 | ##root = Tk() 15 | ##mi_interfaz = Interfaz() 16 | -------------------------------------------------------------------------------- /Codigo/Tkinter/imagenes/abrir_archivo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/imagenes/abrir_archivo.gif -------------------------------------------------------------------------------- /Codigo/Tkinter/imagenes/anadir_pestana.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/imagenes/anadir_pestana.gif -------------------------------------------------------------------------------- /Codigo/Tkinter/imagenes/borrar_pestana.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/imagenes/borrar_pestana.gif -------------------------------------------------------------------------------- /Codigo/Tkinter/imagenes/guardar_archivo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/imagenes/guardar_archivo.gif -------------------------------------------------------------------------------- /Codigo/Tkinter/imagenes/pelota.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/imagenes/pelota.gif -------------------------------------------------------------------------------- /Codigo/Tkinter/imagenes/salir.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Marcombo/desarrollo-de-interficies-graficas-python-tkinter/f0c22949f3f29db359069525c7b6121d06e08081/Codigo/Tkinter/imagenes/salir.gif -------------------------------------------------------------------------------- /Codigo/Tkinter/metodos comunes/metodos_comunes_foco.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Entry 2 | from random import randint 3 | 4 | texto= "tkinter" 5 | periodo = 400 6 | 7 | def modifica_foco(campo_actual): 8 | estado = "EN CURSO" 9 | 10 | texto_campo_actual = campo_actual.get() 11 | if texto[0:len(texto_campo_actual)] != texto_campo_actual: 12 | estado = "KO" 13 | elif texto == campo1.get() == campo2.get() == campo3.get() == campo4.get(): 14 | estado = "OK" 15 | 16 | if estado == "EN CURSO" : 17 | if randint(0, 1): 18 | nuevo_campo = campo_actual.tk_focusNext() 19 | else: 20 | nuevo_campo = campo_actual.tk_focusPrev() 21 | 22 | nuevo_campo.focus_set() 23 | root.after(periodo, modifica_foco, nuevo_campo) 24 | else: 25 | if estado == "OK": 26 | etiqueta = Label(text="¡PRUEBA SUPERADA!", fg = "green", font=("Arial", 20, "bold")) 27 | else : 28 | etiqueta = Label(text="¡PRUEBA NO SUPERADA!", fg = "red", font=("Arial", 20, "bold")) 29 | 30 | campo1.configure(state="disabled") 31 | campo2.configure(state="disabled") 32 | campo3.configure(state="disabled") 33 | campo4.configure(state="disabled") 34 | etiqueta.pack(padx=10, pady=10) 35 | 36 | root = Tk() 37 | root.title("Deletrea") 38 | root.resizable(False, False) 39 | 40 | campo1 = Entry(font=("Arial", 24, "bold"), bd=5, highlightcolor="red", highlightthickness=2) 41 | campo2 = Entry(font=("Arial", 24, "bold"), bd=5, highlightcolor="red", highlightthickness=2) 42 | campo3 = Entry(font=("Arial", 24, "bold"), bd=5, highlightcolor="red", highlightthickness=2) 43 | campo4 = Entry(font=("Arial", 24, "bold"), bd=5, highlightcolor="red", highlightthickness=2) 44 | 45 | campo1.pack(padx=10, pady=10) 46 | campo2.pack(padx=10, pady=10) 47 | campo3.pack(padx=10, pady=10) 48 | campo4.pack(padx=10, pady=10) 49 | 50 | campo1.focus_set() 51 | 52 | modifica_foco(campo1) 53 | 54 | 55 | -------------------------------------------------------------------------------- /Codigo/Tkinter/metodos comunes/metodos_comunes_posicion_raton.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | def mostrar_posicion(): 4 | (x, y) = root.winfo_pointerxy() 5 | root_x = root.winfo_rootx() 6 | root_y = root.winfo_rooty() 7 | ancho_pantalla = root.winfo_width() 8 | alto_pantalla = root.winfo_height() 9 | mouse_x = x - root_x 10 | mouse_y = y - root_y 11 | if mouse_x < 0 or mouse_x > ancho_pantalla or mouse_y < 0 or mouse_y > alto_pantalla: 12 | mouse_x = -1 13 | mouse_y = -1 14 | 15 | etiqueta.configure(text=str(mouse_x) + ", " + str(mouse_y)) 16 | root.after(10, mostrar_posicion) 17 | 18 | root = Tk() 19 | root.geometry("400x200") 20 | 21 | etiqueta = Label(text="-1, -1", font=("Arial", 20, "bold")) 22 | 23 | etiqueta.pack(expand=True) 24 | 25 | mostrar_posicion() 26 | -------------------------------------------------------------------------------- /Codigo/Tkinter/metodos comunes/metodos_comunes_temporizadores.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | incremento = 2 4 | periodo = 50 5 | tamanio_max = 40 6 | tamanio = tamanio_min = 10 7 | 8 | def modifica_tamanio(): 9 | global tamanio, incremento 10 | 11 | 12 | if tamanio > tamanio_max or tamanio < tamanio_min: 13 | incremento = -incremento 14 | tamanio += incremento 15 | 16 | etiqueta.configure( font=("Arial", str(tamanio), "bold")) 17 | 18 | etiqueta.after(periodo, modifica_tamanio) 19 | 20 | root = Tk() 21 | root.geometry("400x200") 22 | 23 | etiqueta = Label(text="¡Qué mareo!", font=("Arial", str(tamanio), "bold")) 24 | 25 | etiqueta.pack(expand=True) 26 | 27 | modifica_tamanio() 28 | -------------------------------------------------------------------------------- /Codigo/Tkinter/opciones comunes/lista_fuentes.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, font 2 | 3 | root = Tk() 4 | print(font.families()) 5 | -------------------------------------------------------------------------------- /Codigo/Tkinter/opciones comunes/opciones_comunes1.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | root = Tk() 4 | 5 | etiqueta = Label(text="¡Hola Mundo!", bg="yellow", fg="blue", font=("Times New Roman", "24", "bold italic")) 6 | 7 | etiqueta.pack(padx=10, pady=10, ipadx=10, ipady=10) 8 | -------------------------------------------------------------------------------- /Codigo/Tkinter/opciones comunes/opciones_comunes2.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Entry 2 | 3 | root = Tk() 4 | 5 | campo1 = Entry(bg="yellow", fg="blue", font=("Times New Roman", "24", "bold italic"), highlightcolor="red", highlightthickness=2) 6 | campo2 = Entry(bg="yellow", fg="blue", font=("Times New Roman", "24", "bold italic"), highlightcolor="red", highlightthickness=2) 7 | campo3 = Entry(bg="yellow", fg="blue", font=("Times New Roman", "24", "bold italic"), highlightcolor="red", highlightthickness=2, takefocus=False) 8 | campo4 = Entry(bg="yellow", fg="blue", font=("Times New Roman", "24", "bold italic"), highlightcolor="red", highlightthickness=2) 9 | 10 | campo1.pack(padx=10, pady=5) 11 | campo2.pack(padx=10, pady=5) 12 | campo3.pack(padx=10, pady=5) 13 | campo4.pack(padx=10, pady=5) 14 | -------------------------------------------------------------------------------- /Codigo/Tkinter/opciones comunes/opciones_comunes3.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | root = Tk() 4 | root.geometry("200x100") 5 | 6 | etiqueta = Label(text="¡Hola Mundo!", width=200, height=100, anchor="se") 7 | etiqueta.pack() 8 | -------------------------------------------------------------------------------- /Codigo/Tkinter/opciones comunes/opciones_comunes4.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Entry 2 | 3 | root = Tk() 4 | root.resizable(False, False) 5 | 6 | etiqueta = Label(text="Campo:") 7 | campo = Entry(relief ="sunken", bd=5) 8 | etiqueta.pack(side="left", padx= 10, pady=20) 9 | campo.pack(side="right", padx=10, pady=20) 10 | 11 | -------------------------------------------------------------------------------- /Codigo/Tkinter/opciones comunes/opciones_comunes5.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | root = Tk() 4 | root.geometry("200x100") 5 | root.configure(cursor="spider") 6 | 7 | etiqueta = Label(relief="raised", text="Reloj", bitmap="hourglass", compound='left') 8 | etiqueta.place(relx=0.5, rely=0.5, anchor="center") 9 | -------------------------------------------------------------------------------- /Codigo/Tkinter/posicionamiento y dise¤o/grid_1.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | filas = 3 4 | columnas = 4 5 | 6 | root = Tk() 7 | 8 | for fila in range(filas): 9 | for columna in range(columnas): 10 | etiqueta = Label(text="Etiqueta"+str(fila)+str(columna), bg="yellow") 11 | etiqueta.grid(row=fila,column=columna, padx=2, pady=2) 12 | 13 | 14 | -------------------------------------------------------------------------------- /Codigo/Tkinter/posicionamiento y dise¤o/grid_2.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | filas = 3 4 | columnas = 4 5 | 6 | root = Tk() 7 | 8 | for fila in range(filas): 9 | root.rowconfigure(fila, weight=1) 10 | for columna in range(columnas): 11 | etiqueta = Label(text="Etiqueta"+str(fila)+str(columna), bg="yellow") 12 | etiqueta.grid(row=fila,column=columna, padx=2, pady=2, sticky="nsew") 13 | #etiqueta.grid(row=fila,column=columna, padx=2, pady=2) 14 | root.columnconfigure(columna, weight=1) 15 | -------------------------------------------------------------------------------- /Codigo/Tkinter/posicionamiento y dise¤o/pack.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, TOP, BOTTOM, LEFT, RIGHT 2 | 3 | root = Tk() 4 | root.geometry("200x200") 5 | 6 | etiqueta1 = Label(text="Etiqueta1") 7 | etiqueta2 = Label(text="Etiqueta2") 8 | etiqueta3 = Label(text="Etiqueta3") 9 | etiqueta4 = Label(text="Etiqueta4") 10 | 11 | ##etiqueta1.pack(padx=10, pady=5) 12 | ##etiqueta2.pack(padx=10, pady=5) 13 | ##etiqueta3.pack(padx=10, pady=5) 14 | ##etiqueta4.pack(padx=10, pady=5) 15 | 16 | etiqueta1.pack(side=TOP, pady=10) 17 | etiqueta2.pack(side=BOTTOM, pady=10) 18 | etiqueta3.pack(side=LEFT, padx=10) 19 | etiqueta4.pack(side=RIGHT, padx=10) 20 | 21 | 22 | -------------------------------------------------------------------------------- /Codigo/Tkinter/posicionamiento y dise¤o/place.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | root = Tk() 4 | root.geometry("200x200") 5 | 6 | etiqueta = Label(text="Etiqueta") 7 | #etiqueta.place(x=100, y=100, anchor="center") 8 | etiqueta.place(relx=0.5, rely=0.5, anchor="center") 9 | 10 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/archivo_texto.txt: -------------------------------------------------------------------------------- 1 | Línea número 1 2 | Línea número 2 3 | Línea número 3 4 | Línea número 4 5 | Línea número 5 6 | Línea número 6 7 | Línea número 7 8 | Línea número 8 9 | Línea número 9 10 | Línea número 10 11 | Línea número 11 12 | Línea número 12 13 | Línea número 13 14 | Línea número 14 15 | Línea número 15 16 | Línea número 16 17 | Línea número 17 18 | Línea número 18 19 | Línea número 19 20 | Línea número 20 21 | Línea número 21 22 | Línea número 22 23 | Línea número 23 24 | Línea número 24 25 | Línea número 25 26 | Línea número 26 27 | Línea número 27 28 | Línea número 28 29 | Línea número 29 30 | Línea número 30 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/archivo_texto2.txt: -------------------------------------------------------------------------------- 1 | Línea número a 2 | Línea número b 3 | Línea número c 4 | Línea número d 5 | Línea número e 6 | Línea número f 7 | Línea número g 8 | Línea número h 9 | Línea número i 10 | Línea número j 11 | Línea número k 12 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_checkbutton_radiobutton.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, IntVar, StringVar, messagebox, ttk 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | 6 | ################################################### 7 | #Funciones que se ejecutan al pulsar los botones 8 | ################################################### 9 | def aceptar(): 10 | selecciones=nombre=edad=sexo=aficiones = "" 11 | 12 | nombre = nombre_entry.get() 13 | direccion = direccion_entry.get() 14 | provincia = var_provincia.get() 15 | edad = edad_entry.get() 16 | sexo = radio_var.get() 17 | aficion1 = check_var1.get() 18 | aficion2 = check_var2.get() 19 | aficion3 = check_var3.get() 20 | if aficion1: aficiones += "Música " 21 | if aficion2: aficiones += "Deporte " 22 | if aficion3: aficiones += "Lectura" 23 | 24 | if nombre:selecciones = "Nombre : "+nombre+"\n" 25 | if direccion:selecciones += "Dirección : "+direccion+"\n" 26 | if provincia != "Pulse para ver las permitidas": 27 | selecciones += "Provincia: "+provincia+"\n" 28 | selecciones += "Edad: "+edad+"\n" 29 | selecciones += "Sexo: "+sexo+"\n" 30 | if aficiones:selecciones += "Aficiones: "+aficiones+"\n" 31 | 32 | messagebox.showinfo("Selección", selecciones) 33 | 34 | def cancelar(): 35 | nombre_entry.delete(0, "end") 36 | direccion_entry.delete(0, "end") 37 | var_provincia.set("Pulse para ver las permitidas") 38 | edad_entry.delete(0, "end") 39 | edad_entry.insert(0, edad_minima) 40 | radio_var.set("Hombre") 41 | check_var1.set(False) 42 | check_var2.set(False) 43 | check_var3.set(False) 44 | 45 | #Ventana principal 46 | root = Tk() 47 | root.title("Formulario") 48 | root.resizable(True, False) 49 | root.minsize(300, 100) 50 | 51 | #Variables de control 52 | var_provincia = StringVar() 53 | radio_var = StringVar() 54 | check_var1 = IntVar() 55 | check_var2 = IntVar() 56 | check_var3 = IntVar() 57 | 58 | ################################################### 59 | #Creación de widgets 60 | ################################################### 61 | 62 | #Creación de la etiqueta y el campo del nombre 63 | nombre_label = ttk.Label(text="Nombre:") 64 | nombre_entry = ttk.Entry() 65 | 66 | #Creación de la etiqueta y el campo de la dirección 67 | direccion_label = ttk.Label(text="Dirección:") 68 | direccion_entry = ttk.Entry() 69 | 70 | #Creación de la etiqueta y el campo de la provincia 71 | provincia_label = ttk.Label(text="Provincia:") 72 | provincia_menu = ttk.OptionMenu(root, var_provincia, "León", "Zamora", "Salamanca", "Valladolid", "Palencia") 73 | var_provincia.set("Pulse para ver las permitidas") 74 | 75 | #Creación de la etiqueta y el campo de la edad 76 | edad_label = ttk.Label(text="Edad:") 77 | edad_entry = ttk.Spinbox(from_=edad_minima, to=edad_maxima, width=3) 78 | edad_entry.insert(0, edad_minima) 79 | 80 | #Creación de la etiqueta, los radiobuttons de sexo y el frame que los contiene 81 | sexo_label = ttk.Label(text="Sexo:") 82 | frame_radiobuttons = ttk.Frame() 83 | hombre_radiobutton = ttk.Radiobutton(frame_radiobuttons, text="Hombre", variable=radio_var, value="Hombre") 84 | mujer_radiobutton = ttk.Radiobutton(frame_radiobuttons, text="Mujer", variable=radio_var, value="Mujer") 85 | radio_var.set("Hombre") 86 | 87 | #Creación de la etiqueta, los radiobuttons de las aficiones y el frame que los contiene 88 | aficiones_label = ttk.Label(text="Aficiones:") 89 | frame_checkbuttons = ttk.Frame() 90 | aficion1_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Música", variable = check_var1) 91 | aficion2_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Deporte", variable = check_var2) 92 | aficion3_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Lectura", variable = check_var3) 93 | 94 | #creación de los botones 95 | boton_aceptar = ttk.Button(text="ACEPTAR", command=aceptar) 96 | boton_cancelar = ttk.Button(text="CANCELAR", command=cancelar) 97 | 98 | ################################################### 99 | #Composición de los widgets en la interfaz 100 | ################################################### 101 | 102 | #Composición de los widgets del nombre 103 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 104 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 105 | 106 | #Composición de los widgets de la dirección 107 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 108 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 109 | 110 | #Composición de los widgets de la provincia 111 | provincia_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 112 | provincia_menu.grid(row=2, column=1, sticky= "w", padx=10) 113 | 114 | #Composición de los widgets de la edad 115 | edad_label.grid(row=3, column=0, sticky= "w", padx=10, pady=10) 116 | edad_entry.grid(row=3, column=1, sticky= "w", padx=10) 117 | 118 | #Permite que los campos de entrada de texto crezcan a lo ancho con la ventana 119 | root.columnconfigure(1, weight=1) 120 | 121 | #Composición de los widgets del sexo 122 | sexo_label.grid(row=4, column=0, sticky= "w", padx=10, pady=10) 123 | frame_radiobuttons.grid(row=4, column=1, sticky= "w", padx=10, pady=10) 124 | hombre_radiobutton.pack(side= "left") 125 | mujer_radiobutton.pack(side= "left") 126 | #hombre_radiobutton.select() 127 | 128 | #Composición de los widgets de las aficiones 129 | aficiones_label.grid(row=5, column=0, sticky= "w", padx=10, pady=10) 130 | frame_checkbuttons.grid(row=5, column=1, sticky= "w", padx=10, pady=10) 131 | aficion1_checkbutton.pack(side= "left") 132 | aficion2_checkbutton.pack(side= "left") 133 | aficion3_checkbutton.pack(side= "left") 134 | 135 | #Composición de los widgets de los botones 136 | boton_aceptar.grid(row=6, column=0, padx=10, pady=10, sticky= "W") 137 | boton_cancelar.grid(row=6, column=1, padx=10, pady=10, sticky= "E") 138 | 139 | root.mainloop() 140 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_combobox.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, IntVar, StringVar, messagebox, ttk 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | lista_provincias = ['León', 'Zamora', 'Salamanca', 'Valladolid', 'Palencia'] 6 | 7 | ################################################### 8 | #Funciones que se ejecutan al pulsar los botones 9 | ################################################### 10 | def aceptar(): 11 | selecciones=nombre=edad=sexo=aficiones = "" 12 | 13 | nombre = nombre_entry.get() 14 | direccion = direccion_entry.get() 15 | provincia = provincia_combobox.get() 16 | edad = edad_entry.get() 17 | sexo = radio_var.get() 18 | aficion1 = check_var1.get() 19 | aficion2 = check_var2.get() 20 | aficion3 = check_var3.get() 21 | if aficion1: aficiones += "Música " 22 | if aficion2: aficiones += "Deporte " 23 | if aficion3: aficiones += "Lectura" 24 | 25 | if nombre:selecciones = "Nombre : "+nombre+"\n" 26 | if direccion:selecciones += "Dirección : "+direccion+"\n" 27 | if provincia: selecciones += "Provincia: "+provincia+"\n" 28 | selecciones += "Edad: "+edad+"\n" 29 | selecciones += "Sexo: "+sexo+"\n" 30 | if aficiones:selecciones += "Aficiones: "+aficiones+"\n" 31 | 32 | messagebox.showinfo("Selección", selecciones) 33 | 34 | def cancelar(): 35 | nombre_entry.delete(0, "end") 36 | direccion_entry.delete(0, "end") 37 | provincia_combobox.set("") 38 | edad_entry.delete(0, "end") 39 | edad_entry.insert(0, edad_minima) 40 | radio_var.set("Hombre") 41 | check_var1.set(False) 42 | check_var2.set(False) 43 | check_var3.set(False) 44 | 45 | #Ventana principal 46 | root = Tk() 47 | root.title("Formulario") 48 | root.resizable(True, False) 49 | root.minsize(300, 100) 50 | 51 | 52 | #Variables de control 53 | radio_var = StringVar() 54 | check_var1 = IntVar() 55 | check_var2 = IntVar() 56 | check_var3 = IntVar() 57 | 58 | ################################################### 59 | #Creación de widgets 60 | ################################################### 61 | 62 | #Creación de la etiqueta y el campo del nombre 63 | nombre_label = ttk.Label(text="Nombre:") 64 | nombre_entry = ttk.Entry() 65 | 66 | #Creación de la etiqueta y el campo de la dirección 67 | direccion_label = ttk.Label(text="Dirección:") 68 | direccion_entry = ttk.Entry() 69 | 70 | #Creación de la etiqueta y el campo de la provincia 71 | provincia_label = ttk.Label(text="Provincia:") 72 | provincia_combobox = ttk.Combobox(values=lista_provincias) 73 | 74 | #Creación de la etiqueta y el campo de la edad 75 | edad_label = ttk.Label(text="Edad:") 76 | edad_entry = ttk.Spinbox(from_=edad_minima, to=edad_maxima, width=3) 77 | edad_entry.insert(0, edad_minima) 78 | 79 | #Creación de la etiqueta, los radiobuttons de sexo y el frame que los contiene 80 | sexo_label = ttk.Label(text="Sexo:") 81 | frame_radiobuttons = ttk.Frame() 82 | hombre_radiobutton = ttk.Radiobutton(frame_radiobuttons, text="Hombre", variable=radio_var, value="Hombre") 83 | mujer_radiobutton = ttk.Radiobutton(frame_radiobuttons, text="Mujer", variable=radio_var, value="Mujer") 84 | radio_var.set("Hombre") 85 | 86 | #Creación de la etiqueta, los radiobuttons de las aficiones y el frame que los contiene 87 | aficiones_label = ttk.Label(text="Aficiones:") 88 | frame_checkbuttons = ttk.Frame() 89 | aficion1_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Música", variable = check_var1) 90 | aficion2_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Deporte", variable = check_var2) 91 | aficion3_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Lectura", variable = check_var3) 92 | 93 | #creación de los botones 94 | boton_aceptar = ttk.Button(text="ACEPTAR", command=aceptar) 95 | boton_cancelar = ttk.Button(text="CANCELAR", command=cancelar) 96 | 97 | ################################################### 98 | #Composición de los widgets en la interfaz 99 | ################################################### 100 | 101 | #Composición de los widgets del nombre 102 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 103 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 104 | 105 | #Composición de los widgets de la dirección 106 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 107 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 108 | 109 | #Composición de los widgets de la provincia 110 | provincia_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 111 | provincia_combobox.grid(row=2, column=1, sticky= "w", padx=10) 112 | 113 | #Composición de los widgets de la edad 114 | edad_label.grid(row=3, column=0, sticky= "w", padx=10, pady=10) 115 | edad_entry.grid(row=3, column=1, sticky= "w", padx=10) 116 | 117 | #Permite que los campos de entrada de texto crezcan a lo ancho con la ventana 118 | root.columnconfigure(1, weight=1) 119 | 120 | #Composición de los widgets del sexo 121 | sexo_label.grid(row=4, column=0, sticky= "w", padx=10, pady=10) 122 | frame_radiobuttons.grid(row=4, column=1, sticky= "w", padx=10, pady=10) 123 | hombre_radiobutton.pack(side= "left") 124 | mujer_radiobutton.pack(side= "left") 125 | 126 | #Composición de los widgets de las aficiones 127 | aficiones_label.grid(row=5, column=0, sticky= "w", padx=10, pady=10) 128 | frame_checkbuttons.grid(row=5, column=1, sticky= "w", padx=10, pady=10) 129 | aficion1_checkbutton.pack(side= "left") 130 | aficion2_checkbutton.pack(side= "left") 131 | aficion3_checkbutton.pack(side= "left") 132 | 133 | #Composición de los widgets de los botones 134 | boton_aceptar.grid(row=6, column=0, padx=10, pady=10, sticky= "W") 135 | boton_cancelar.grid(row=6, column=1, padx=10, pady=10, sticky= "E") 136 | 137 | root.mainloop() 138 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_estilos.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, ttk 2 | 3 | root = Tk() 4 | root.minsize(200, 100) 5 | 6 | estilo = ttk.Style() 7 | estilo.configure("miEstilo.TLabel", foreground="white", background="blue", font=("Arial", 20, "bold italic"), anchor="center") 8 | 9 | etiqueta = ttk.Label(text="Botón ttk", style="miEstilo.TLabel") 10 | etiqueta.pack(expand= True, padx= 20, pady=20, ipadx=10, ipady=10) 11 | 12 | ##MODIFICACIÓN DE LAS OPCIONES DE UN ESTILO PREDETERMINADO 13 | ##from tkinter import Tk, ttk 14 | ## 15 | ##root = Tk() 16 | ##root.minsize(200, 100) 17 | ## 18 | ##estilo = ttk.Style() 19 | ##estilo.configure("TLabel", foreground="white", background="red", font=("Arial", 20, "bold"), anchor="center") 20 | ## 21 | ##etiqueta = ttk.Label(text="Botón ttk") 22 | ##etiqueta.pack(expand= True, padx= 20, pady=20, ipadx=10, ipady=10) 23 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_mapa_estados.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, ttk 2 | 3 | root = Tk() 4 | 5 | estilo = ttk.Style() 6 | estilo.configure('miEstilo.TButton', font=('Arial', 24)) 7 | estilo.map('miEstilo.TButton', foreground=[('pressed', 'blue'),('active', 'orange')], font=[('active', ('Arial', 28, 'bold'))]) 8 | 9 | boton = ttk.Button(style='miEstilo.TButton', text="Botón") 10 | boton.pack(padx=10, pady=10, ipadx=5, ipady=5) 11 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_notebook.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Text, Button, PhotoImage, filedialog, messagebox, ttk 2 | from pathlib import Path 3 | 4 | ################################################### 5 | #Funciones que se ejecutan al pulsar los botones 6 | ################################################### 7 | def anadir_pestana(): 8 | frame_editor = ttk.Frame() 9 | area_texto = Text(frame_editor) 10 | scrollbar = ttk.Scrollbar(frame_editor, command=area_texto.yview) 11 | area_texto.config(yscrollcommand = scrollbar.set) 12 | area_texto.pack(expand= True, fill="both", side = "left") 13 | scrollbar.pack(side = "right", fill = "y") 14 | editor.add(frame_editor, text="(vacío)") 15 | if len(editor.tabs()) > 1: 16 | posicion_etiqueta_actual = editor.index('current') 17 | editor.select(posicion_etiqueta_actual+1) 18 | 19 | def borrar_pestana(): 20 | if len(editor.tabs()) > 0: 21 | posicion_etiqueta = editor.index('current') 22 | editor.forget(posicion_etiqueta) 23 | 24 | def guardar(): 25 | if len(editor.tabs()) == 0: return 26 | posicion_etiqueta = editor.index('current') 27 | etiqueta = editor.tab(posicion_etiqueta, option='text') 28 | id_frame_editor = editor.select() 29 | frame_editor = editor.nametowidget(id_frame_editor) 30 | lista_widgets = frame_editor.winfo_children() 31 | area_texto = lista_widgets[0] 32 | 33 | if etiqueta == "(vacío)": 34 | fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 35 | else: 36 | fichero = etiqueta + ".txt" 37 | 38 | if fichero: 39 | etiqueta = Path(fichero).stem 40 | editor.tab(posicion_etiqueta, text=etiqueta) 41 | texto = area_texto.get(1.0, "end") 42 | f = open(fichero, "w", encoding='utf-8') 43 | f.write(texto) 44 | f.close 45 | messagebox.showinfo("Guardar", fichero+" guardado correctamente.") 46 | 47 | def abrir(): 48 | fichero = filedialog.askopenfilename(initialdir = ".", title = "Abrir archivo", filetypes = [("ficheros texto", "*.txt")]) 49 | etiqueta = Path(fichero).stem 50 | if fichero: 51 | frame_editor = ttk.Frame() 52 | area_texto = Text(frame_editor) 53 | scrollbar = ttk.Scrollbar(frame_editor, command=area_texto.yview) 54 | area_texto.config(yscrollcommand = scrollbar.set) 55 | area_texto.pack(expand= True, fill="both", side = "left") 56 | scrollbar.pack(side = "right", fill = "y") 57 | editor.add(frame_editor, text=etiqueta) 58 | if len(editor.tabs()) > 1: editor.select(editor.index('current')+1) 59 | 60 | f = open(fichero, "r", encoding='utf-8') 61 | area_texto.insert(1.0, f.read()) 62 | f.close() 63 | 64 | ################################################### 65 | #Ventana principal 66 | ################################################### 67 | root = Tk() 68 | root.title("Editor de texto") 69 | root.minsize(600, 300) 70 | 71 | ################################################### 72 | #Barra de herramientas 73 | ################################################### 74 | barra_herramientas = ttk.Frame() 75 | img_anadir_pestana = PhotoImage(file="../imagenes/anadir_pestana.gif") 76 | img_borrar_pestana = PhotoImage(file="../imagenes/borrar_pestana.gif") 77 | img_abrir_archivo = PhotoImage(file="../imagenes/abrir_archivo.gif") 78 | img_guardar_archivo = PhotoImage(file="../imagenes/guardar_archivo.gif") 79 | boton_anadir_pestana = Button(barra_herramientas,image=img_anadir_pestana, background="white", command=anadir_pestana) 80 | boton_borrar_pestana = Button(barra_herramientas,image=img_borrar_pestana, background="white", command=borrar_pestana) 81 | boton_abrir_archivo = Button(barra_herramientas,image=img_abrir_archivo, background="white", command=abrir) 82 | boton_guardar_archivo = Button(barra_herramientas,image=img_guardar_archivo, background="white", command=guardar) 83 | boton_anadir_pestana.pack(side="left", padx=5, pady=5) 84 | boton_borrar_pestana.pack(side="left") 85 | boton_guardar_archivo.pack(side="right", padx=5, pady=5) 86 | boton_abrir_archivo.pack(side="right") 87 | barra_herramientas.pack(fill="x") 88 | 89 | ################################################### 90 | #Notebook 91 | ################################################### 92 | editor = ttk.Notebook() 93 | editor.pack(expand= True, fill="both") 94 | 95 | root.mainloop() 96 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_progressbar.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, ttk 2 | import time, threading 3 | 4 | def proceso(): 5 | boton.configure(state='disabled') 6 | barra_progreso.grid(row=1) 7 | for i in range (0, 100, 10): 8 | time.sleep(0.5) 9 | barra_progreso.step(10) 10 | barra_progreso.grid_forget() 11 | boton.configure(state='enabled') 12 | 13 | def arrancar_proceso(): 14 | hilo = threading.Thread(target=proceso) 15 | hilo.start() 16 | 17 | root = Tk() 18 | root.geometry("200x100") 19 | root.resizable(False, False) 20 | root.columnconfigure(0,weight=1) 21 | 22 | boton = ttk.Button(text="PULSAR", command=arrancar_proceso) 23 | boton.grid(row=0, pady=20) 24 | 25 | barra_progreso = ttk.Progressbar() 26 | 27 | root.mainloop() 28 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_separator.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, IntVar, StringVar, messagebox, ttk 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | lista_provincias = ['León', 'Zamora', 'Salamanca', 'Valladolid', 'Palencia'] 6 | 7 | ################################################### 8 | #Funciones que se ejecutan al pulsar los botones 9 | ################################################### 10 | def aceptar(): 11 | selecciones=nombre=edad=sexo=aficiones = "" 12 | 13 | nombre = nombre_entry.get() 14 | direccion = direccion_entry.get() 15 | provincia = provincia_combobox.get() 16 | edad = edad_entry.get() 17 | sexo = radio_var.get() 18 | aficion1 = check_var1.get() 19 | aficion2 = check_var2.get() 20 | aficion3 = check_var3.get() 21 | if aficion1: aficiones += "Música " 22 | if aficion2: aficiones += "Deporte " 23 | if aficion3: aficiones += "Lectura" 24 | 25 | if nombre:selecciones = "Nombre : "+nombre+"\n" 26 | if direccion:selecciones += "Dirección : "+direccion+"\n" 27 | if provincia: selecciones += "Provincia: "+provincia+"\n" 28 | selecciones += "Edad: "+edad+"\n" 29 | selecciones += "Sexo: "+sexo+"\n" 30 | if aficiones:selecciones += "Aficiones: "+aficiones+"\n" 31 | 32 | messagebox.showinfo("Selección", selecciones) 33 | 34 | def cancelar(): 35 | nombre_entry.delete(0, "end") 36 | direccion_entry.delete(0, "end") 37 | provincia_combobox.set("") 38 | edad_entry.delete(0, "end") 39 | edad_entry.insert(0, edad_minima) 40 | radio_var.set("Hombre") 41 | check_var1.set(False) 42 | check_var2.set(False) 43 | check_var3.set(False) 44 | 45 | #Ventana principal 46 | root = Tk() 47 | root.title("Formulario") 48 | root.resizable(True, False) 49 | root.minsize(300, 100) 50 | 51 | 52 | #Variables de control 53 | radio_var = StringVar() 54 | check_var1 = IntVar() 55 | check_var2 = IntVar() 56 | check_var3 = IntVar() 57 | 58 | ################################################### 59 | #Creación de widgets 60 | ################################################### 61 | 62 | #Creación de la etiqueta y el campo del nombre 63 | nombre_label = ttk.Label(text="Nombre:") 64 | nombre_entry = ttk.Entry() 65 | 66 | #Creación de la etiqueta y el campo de la dirección 67 | direccion_label = ttk.Label(text="Dirección:") 68 | direccion_entry = ttk.Entry() 69 | 70 | #Creación de la etiqueta y el campo de la provincia 71 | provincia_label = ttk.Label(text="Provincia:") 72 | provincia_combobox = ttk.Combobox(values=lista_provincias) 73 | 74 | #Creación del separador 75 | separador = ttk.Separator() 76 | 77 | #Creación de la etiqueta y el campo de la edad 78 | edad_label = ttk.Label(text="Edad:") 79 | edad_entry = ttk.Spinbox(from_=edad_minima, to=edad_maxima, width=3) 80 | edad_entry.insert(0, edad_minima) 81 | 82 | #Creación de la etiqueta, los radiobuttons de sexo y el frame que los contiene 83 | sexo_label = ttk.Label(text="Sexo:") 84 | frame_radiobuttons = ttk.Frame() 85 | hombre_radiobutton = ttk.Radiobutton(frame_radiobuttons, text="Hombre", variable=radio_var, value="Hombre") 86 | mujer_radiobutton = ttk.Radiobutton(frame_radiobuttons, text="Mujer", variable=radio_var, value="Mujer") 87 | radio_var.set("Hombre") 88 | 89 | #Creación de la etiqueta, los radiobuttons de las aficiones y el frame que los contiene 90 | aficiones_label = ttk.Label(text="Aficiones:") 91 | frame_checkbuttons = ttk.Frame() 92 | aficion1_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Música", variable = check_var1) 93 | aficion2_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Deporte", variable = check_var2) 94 | aficion3_checkbutton = ttk.Checkbutton(frame_checkbuttons, text = "Lectura", variable = check_var3) 95 | 96 | #creación de los botones 97 | boton_aceptar = ttk.Button(text="ACEPTAR", command=aceptar) 98 | boton_cancelar = ttk.Button(text="CANCELAR", command=cancelar) 99 | 100 | ################################################### 101 | #Composición de los widgets en la interfaz 102 | ################################################### 103 | 104 | #Composición de los widgets del nombre 105 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 106 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 107 | 108 | #Composición de los widgets de la dirección 109 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 110 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 111 | 112 | #Composición de los widgets de la provincia 113 | provincia_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 114 | provincia_combobox.grid(row=2, column=1, sticky= "w", padx=10) 115 | 116 | #Composición del separador 117 | separador.grid(row=3, column=0, sticky= "ew", columnspan=2, padx=10, pady=10) 118 | 119 | #Composición de los widgets de la edad 120 | edad_label.grid(row=4, column=0, sticky= "w", padx=10, pady=10) 121 | edad_entry.grid(row=4, column=1, sticky= "w", padx=10) 122 | 123 | #Permite que los campos de entrada de texto crezcan a lo ancho con la ventana 124 | root.columnconfigure(1, weight=1) 125 | 126 | #Composición de los widgets del sexo 127 | sexo_label.grid(row=5, column=0, sticky= "w", padx=10, pady=10) 128 | frame_radiobuttons.grid(row=5, column=1, sticky= "w", padx=10, pady=10) 129 | hombre_radiobutton.pack(side= "left") 130 | mujer_radiobutton.pack(side= "left") 131 | 132 | #Composición de los widgets de las aficiones 133 | aficiones_label.grid(row=6, column=0, sticky= "w", padx=10, pady=10) 134 | frame_checkbuttons.grid(row=6, column=1, sticky= "w", padx=10, pady=10) 135 | aficion1_checkbutton.pack(side= "left") 136 | aficion2_checkbutton.pack(side= "left") 137 | aficion3_checkbutton.pack(side= "left") 138 | 139 | #Composición de los widgets de los botones 140 | boton_aceptar.grid(row=7, column=0, padx=10, pady=10, sticky= "W") 141 | boton_cancelar.grid(row=7, column=1, padx=10, pady=10, sticky= "E") 142 | 143 | root.mainloop() 144 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ttk/ttk_sizegrip.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Text, Button, PhotoImage, filedialog, messagebox, ttk 2 | from pathlib import Path 3 | 4 | ################################################### 5 | #Funciones que se ejecutan al pulsar los botones 6 | ################################################### 7 | def anadir_pestana(): 8 | marco_editor = ttk.Frame() 9 | area_texto = Text(marco_editor) 10 | scrollbar = ttk.Scrollbar(marco_editor, command=area_texto.yview) 11 | area_texto.config(yscrollcommand = scrollbar.set) 12 | area_texto.pack(expand= True, fill="both", side = "left") 13 | scrollbar.pack(side = "right", fill = "y") 14 | editor.add(marco_editor, text="(vacío)") 15 | if len(editor.tabs()) > 1: editor.select(editor.index('current')+1) 16 | 17 | def borrar_pestana(): 18 | if len(editor.tabs()) > 0: 19 | posicion_etiqueta = editor.index('current') 20 | editor.forget(posicion_etiqueta) 21 | 22 | def guardar(): 23 | posicion_etiqueta = editor.index('current') 24 | etiqueta = editor.tab(posicion_etiqueta, option='text') 25 | id_marco_editor = editor.select() 26 | marco_editor = editor.nametowidget(id_marco_editor) 27 | lista_widgets = marco_editor.winfo_children() 28 | area_texto = lista_widgets[0] 29 | 30 | if etiqueta == "(vacío)": 31 | fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 32 | etiqueta = Path(fichero).stem 33 | editor.tab(posicion_etiqueta, text=etiqueta) 34 | else: 35 | fichero = etiqueta + ".txt" 36 | 37 | texto = area_texto.get(1.0, "end") 38 | f = open(fichero, "w", encoding='utf-8') 39 | f.write(texto) 40 | f.close 41 | messagebox.showinfo("Guardar", fichero+" guardado correctamente.") 42 | 43 | def abrir(): 44 | fichero = filedialog.askopenfilename(initialdir = ".", title = "Abrir archivo", filetypes = [("ficheros texto", "*.txt")]) 45 | etiqueta = Path(fichero).stem 46 | if fichero: 47 | marco_editor = ttk.Frame() 48 | area_texto = Text(marco_editor) 49 | scrollbar = ttk.Scrollbar(marco_editor, command=area_texto.yview) 50 | area_texto.config(yscrollcommand = scrollbar.set) 51 | area_texto.pack(expand= True, fill="both", side = "left") 52 | scrollbar.pack(side = "right", fill = "y") 53 | editor.add(marco_editor, text=etiqueta) 54 | if len(editor.tabs()) > 1: editor.select(editor.index('current')+1) 55 | 56 | f = open(fichero, "r", encoding='utf-8') 57 | area_texto.insert(1.0, f.read()) 58 | f.close() 59 | 60 | ################################################### 61 | #Ventana principal 62 | ################################################### 63 | root = Tk() 64 | root.title("Editor de texto") 65 | root.minsize(600, 300) 66 | 67 | ################################################### 68 | #Barra de herramientas 69 | ################################################### 70 | barra_herramientas = ttk.Frame() 71 | img_anadir_pestana = PhotoImage(file="../imagenes/anadir_pestana.gif") 72 | img_borrar_pestana = PhotoImage(file="../imagenes/borrar_pestana.gif") 73 | img_abrir_archivo = PhotoImage(file="../imagenes/abrir_archivo.gif") 74 | img_guardar_archivo = PhotoImage(file="../imagenes/guardar_archivo.gif") 75 | boton_anadir_pestana = Button(barra_herramientas,image=img_anadir_pestana, background="white", command=anadir_pestana) 76 | boton_borrar_pestana = Button(barra_herramientas,image=img_borrar_pestana, background="white", command=borrar_pestana) 77 | boton_abrir_archivo = Button(barra_herramientas,image=img_abrir_archivo, background="white", command=abrir) 78 | boton_guardar_archivo = Button(barra_herramientas,image=img_guardar_archivo, background="white", command=guardar) 79 | boton_anadir_pestana.pack(side="left", padx=5, pady=5) 80 | boton_borrar_pestana.pack(side="left") 81 | boton_guardar_archivo.pack(side="right", padx=5, pady=5) 82 | boton_abrir_archivo.pack(side="right") 83 | barra_herramientas.pack(fill="x") 84 | 85 | ################################################### 86 | #Notebook 87 | ################################################### 88 | editor = ttk.Notebook() 89 | editor.pack(expand= True, fill="both") 90 | 91 | ################################################### 92 | #Sizegrip 93 | ################################################### 94 | sg = ttk.Sizegrip() 95 | sg.pack(side="right") 96 | 97 | root.mainloop() 98 | -------------------------------------------------------------------------------- /Codigo/Tkinter/validacion entrada de datos/validacion_entrada_datos.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Spinbox 2 | 3 | def validar_edad(edad): 4 | return edad == "" or edad.isdigit() and len(edad) <= 2 5 | 6 | root = Tk() 7 | root.resizable(False, False) 8 | 9 | edad_label = Label(text="Edad:") 10 | identificador = root.register(validar_edad) 11 | vc = (identificador, '%P') 12 | edad_entry = Spinbox(from_=1, to=99, width=3, bd=5, highlightcolor="red", highlightthickness=2, validate="key", validatecommand=vc) 13 | 14 | edad_label.grid(row=0, column=0, sticky= "w", padx=20, pady=10) 15 | edad_entry.grid(row=0, column=1, sticky= "w", padx=20, pady=10) 16 | -------------------------------------------------------------------------------- /Codigo/Tkinter/variables de control/variables_control.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, StringVar 2 | 3 | texto = "¡Hola Mundo!" 4 | intervalo = 200 5 | 6 | texto_auxiliar = texto + " " * len(texto) 7 | 8 | def avanza(): 9 | global texto_auxiliar 10 | 11 | ultimo_caracter = texto_auxiliar[len(texto_auxiliar) - 1] 12 | texto_auxiliar = texto_auxiliar[:-1] 13 | texto_auxiliar = ultimo_caracter + texto_auxiliar 14 | variable_control.set(texto_auxiliar[0:len(texto)]) 15 | root.after(intervalo, avanza) 16 | 17 | root = Tk() 18 | root.title("Letrero deslizante") 19 | 20 | variable_control = StringVar() 21 | 22 | etiqueta = Label(textvariable=variable_control, width= len(texto), padx=10, pady=10, fg="blue", font=("Arial", "48", "bold")) 23 | etiqueta.pack() 24 | 25 | avanza() 26 | 27 | root.mainloop() 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Codigo/Tkinter/ventana principal/ventana_principal.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label 2 | 3 | root = Tk() 4 | root.geometry("200x50") 5 | root.resizable(True, False) 6 | root.minsize(50, 50) 7 | root.maxsize(400, 50) 8 | 9 | etiqueta = Label(text="\n ¡Hola Mundo! \n") 10 | etiqueta.pack() 11 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/archivo_texto.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Línea número 1

4 |

Línea número 2

5 |

Línea número 3

6 |

Línea número 4

7 |

Línea número 5

8 |

Línea número 6

9 |

Línea número 7

10 |

Línea número 8

11 |

Línea número 9

12 |

Línea número 10

13 |

Línea número 11

14 |

Línea número 12

15 |

Línea número 13

16 |

Línea número 14

17 |

Línea número 15

18 |

Línea número 16

19 |

Línea número 17

20 |

Línea número 18

21 |

Línea número 19

22 |

Línea número 21

23 |

Línea número 22

24 |

Línea número 23

25 |

Línea número 24

26 |

Línea número 25

27 |

Línea número 26

28 |

Línea número 27

29 |

Línea número 28

30 |

Línea número 29

31 |

Línea número 30

32 | 33 | 34 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/archivo_texto.txt: -------------------------------------------------------------------------------- 1 | Línea número 1 2 | Línea número 2 3 | Línea número 3 4 | Línea número 4 5 | Línea número 5 6 | Línea número 6 7 | Línea número 7 8 | Línea número 8 9 | Línea número 9 10 | Línea número 10 11 | Línea número 11 12 | Línea número 12 13 | Línea número 13 14 | Línea número 14 15 | Línea número 15 16 | Línea número 16 17 | Línea número 17 18 | Línea número 18 19 | Línea número 19 20 | Línea número 20 21 | Línea número 21 22 | Línea número 22 23 | Línea número 23 24 | Línea número 24 25 | Línea número 25 26 | Línea número 26 27 | Línea número 27 28 | Línea número 28 29 | Línea número 29 30 | Línea número 30 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/archivo_texto2.txt: -------------------------------------------------------------------------------- 1 | Línea número a 2 | Línea número b 3 | Línea número c 4 | Línea número d 5 | Línea número e 6 | Línea número f 7 | Línea número g 8 | Línea número h 9 | Línea número i 10 | Línea número j 11 | Línea número k 12 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/button.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Button, StringVar 2 | 3 | hora=minuto=segundo=0 4 | inicio=False 5 | 6 | def actualizar_tiempo(): 7 | global hora, minuto, segundo 8 | 9 | if inicio: 10 | segundo += 1 11 | if segundo == 60: 12 | segundo = 0 13 | minuto += 1 14 | if minuto == 60: 15 | segundo = 0 16 | minuto = 0 17 | hora += 1 18 | if hora == 99: 19 | segundo = 0 20 | minuto = 0 21 | hora = 0 22 | if hora < 10: hora_str = "0"+str(hora) 23 | else: hora_str = str(hora) 24 | if minuto < 10: minuto_str = "0"+str(minuto) 25 | else: minuto_str = str(minuto) 26 | if segundo < 10: segundo_str = "0"+str(segundo) 27 | else: segundo_str = str(segundo) 28 | variable_control.set(hora_str+":"+minuto_str+":"+segundo_str) 29 | root.after(1000, actualizar_tiempo) 30 | 31 | def start(): 32 | global hora, minuto, segundo, inicio 33 | 34 | if not(inicio): 35 | variable_control.set("00:00:00") 36 | hora=minuto=segundo=0 37 | inicio=True 38 | root.after(1000, actualizar_tiempo) 39 | 40 | def stop(): 41 | global inicio 42 | inicio=False 43 | 44 | root = Tk() 45 | root.resizable(False, False) 46 | 47 | variable_control = StringVar(value="00:00:00") 48 | 49 | reloj = Label(textvariable= variable_control, fg="blue", font=("Arial", 18), padx=20, pady=20) 50 | boton_start = Button(text="Start", padx=10, fg="white", bg="green", command=start) 51 | boton_stop = Button(text="Stop", padx=10, fg="white", bg="red", command=stop) 52 | 53 | reloj.pack() 54 | boton_start.pack(side="left", padx=10, pady=10) 55 | boton_stop.pack(side="right", padx=10, pady=10) 56 | 57 | root.mainloop() 58 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_arc.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | 3 | ancho = 300 4 | alto = 200 5 | 6 | radio_ojo = 10 7 | radio_cara = 100 8 | angulo_inicial_max = angulo_inicial = 30 9 | apertura = 300 10 | incremento = 5 11 | 12 | periodo = 50 13 | 14 | def mueve_boca(): 15 | global incremento, angulo_inicial, apertura 16 | 17 | angulo_inicial -= incremento 18 | apertura += 2*incremento 19 | if angulo_inicial <= incremento or angulo_inicial >= angulo_inicial_max: 20 | incremento = -incremento 21 | 22 | canvas.itemconfig(cara, extent=apertura, start=angulo_inicial) 23 | canvas.after(periodo, mueve_boca) 24 | 25 | root = Tk() 26 | root.resizable(False, False) 27 | 28 | canvas = Canvas(width=ancho, height=alto) 29 | cara = canvas.create_arc(ancho/2-radio_cara, alto/2-radio_cara, ancho/2+radio_cara, alto/2+radio_cara, start=angulo_inicial, extent=apertura, fill="blue", outline="") 30 | ojo = canvas.create_oval(ancho/2-radio_ojo, alto/4-radio_ojo, ancho/2+radio_ojo, alto/4+radio_ojo, fill="yellow", outline="") 31 | 32 | canvas.pack() 33 | 34 | mueve_boca() 35 | 36 | root.mainloop() 37 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_circulo.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | from random import randint 3 | 4 | radio = 10 5 | ancho = 400 6 | alto = 200 7 | desplazamiento_x = 1 8 | desplazamiento_y = 1 9 | intervalo = 2 10 | 11 | centro_x = randint(radio, ancho) 12 | centro_y = randint(radio, alto) 13 | 14 | def mueve_pelota(): 15 | global desplazamiento_x, desplazamiento_y 16 | 17 | x0, y0, x1, y1 = canvas.coords(pelota) 18 | if x0 < 0 or x1 > ancho: desplazamiento_x = -desplazamiento_x 19 | if y0 < 0 or y1 > alto: desplazamiento_y = -desplazamiento_y 20 | canvas.move(pelota, desplazamiento_x, desplazamiento_y) 21 | root.after(intervalo, mueve_pelota) 22 | 23 | 24 | root = Tk() 25 | root.resizable(False,False) 26 | canvas = Canvas(width = ancho, height = alto) 27 | canvas.pack() 28 | 29 | pelota = canvas.create_oval(centro_x-radio, centro_y-radio, centro_x+radio, centro_y+radio, fill="blue", outline="blue") 30 | mueve_pelota() 31 | 32 | root.mainloop() 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_imagen.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas, PhotoImage 2 | from random import randint 3 | 4 | radio = 20 5 | ancho = 400 6 | alto = 200 7 | desplazamiento_x = 1 8 | desplazamiento_y = 1 9 | intervalo = 2 10 | 11 | centro_x = randint(radio, ancho) 12 | centro_y = randint(radio, alto) 13 | 14 | def mueve_pelota(): 15 | global desplazamiento_x, desplazamiento_y 16 | 17 | x, y = canvas.coords(pelota) 18 | if x-radio < 0 or x+radio > ancho: desplazamiento_x = -desplazamiento_x 19 | if y-radio < 0 or y+radio > alto: desplazamiento_y = -desplazamiento_y 20 | canvas.move(pelota, desplazamiento_x, desplazamiento_y) 21 | root.after(intervalo, mueve_pelota) 22 | 23 | root = Tk() 24 | root.resizable(False,False) 25 | canvas = Canvas(width = ancho, height = alto, bg="white") 26 | canvas.pack() 27 | 28 | img = PhotoImage(file="../imagenes/pelota.gif") 29 | pelota = canvas.create_image(centro_x, centro_y, image=img, anchor="center") 30 | 31 | mueve_pelota() 32 | 33 | root.mainloop() 34 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_lineas.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | 3 | ancho = 400 4 | alto = 200 5 | intervalo = 50 6 | 7 | root = Tk() 8 | root.resizable(False, False) 9 | 10 | canvas = Canvas(width=ancho, height=alto) 11 | 12 | for x in range(0, ancho, intervalo): 13 | canvas.create_line(x,0, x, alto) 14 | for y in range(0, alto, intervalo): 15 | canvas.create_line(0,y, ancho, y) 16 | 17 | canvas.pack() 18 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_poligono.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | 3 | root = Tk() 4 | root.resizable(False, False) 5 | 6 | canvas = Canvas(width=400, height=200) 7 | rectangulo = canvas.create_polygon(100, 50, 300, 150, 300, 50, 100, 150, fill="yellow", outline="orange", width=5) 8 | canvas.pack() 9 | 10 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_rectangulo.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | 3 | periodo = 200 4 | var_aux = False 5 | 6 | def mueve_dash(): 7 | global var_aux 8 | 9 | if var_aux: patron=(6, 4, 2, 4) 10 | else:patron=(6, 4, 2, 4, 2, 4) 11 | canvas.itemconfigure(rectangulo, dash=patron) 12 | var_aux = not(var_aux) 13 | root.after(periodo, mueve_dash) 14 | 15 | root = Tk() 16 | root.geometry("400x200") 17 | root.resizable(False, False) 18 | 19 | canvas = Canvas() 20 | rectangulo = canvas.create_rectangle(50, 50, 350, 150, fill="yellow", outline="blue", width=5) 21 | canvas.pack() 22 | 23 | mueve_dash() 24 | 25 | root.mainloop() 26 | 27 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/canvas_text.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | 3 | root = Tk() 4 | root.resizable(False,False) 5 | canvas = Canvas(width = 400, height = 200) 6 | texto=canvas.create_text(200, 100, anchor="center", text="Acerca el ratón al texto", font=("Arial", "20", "bold"), fill="blue", activefill="red") 7 | 8 | canvas.pack() 9 | 10 | root.mainloop() 11 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/checkbutton_editor_texto.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Menu, Text, PhotoImage, filedialog, IntVar 2 | 3 | fichero="" 4 | extensiones = [("ficheros texto", "*.txt")] 5 | 6 | ########################################################## 7 | #Funciones que se ejecutan seleccionar una opción del menú 8 | ########################################################## 9 | 10 | def nuevo(): 11 | global fichero 12 | 13 | area_texto.delete(1.0, "end") 14 | fichero = "" 15 | 16 | def abrir(): 17 | global fichero 18 | 19 | fichero = filedialog.askopenfilename(initialdir = ".", title = "Abrir archivo", \ 20 | filetypes = extensiones) 21 | if fichero: 22 | f = open(fichero, "r", encoding='utf-8') 23 | area_texto.delete(1.0, "end") 24 | area_texto.insert("insert", f.read()) 25 | f.close() 26 | 27 | def guardar(): 28 | global fichero 29 | if not(fichero): fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar", \ 30 | filetypes = extensiones, \ 31 | defaultextension=".txt") 32 | if fichero: 33 | texto = area_texto.get(1.0, "end") 34 | f = open(fichero, "w", encoding='utf-8') 35 | f.write(texto) 36 | f.close 37 | 38 | def guardar_como(): 39 | global fichero 40 | 41 | fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar como", filetypes = extensiones, defaultextension=[".txt", ".html"]) 42 | if fichero: 43 | texto = area_texto.get(1.0, "end") 44 | f = open(fichero, "w", encoding='utf-8') 45 | f.write(texto) 46 | f.close 47 | 48 | def gestion_extensiones(): 49 | global extensiones 50 | 51 | extensiones = [("ficheros texto", "*.txt")] 52 | if extension_xml.get(): 53 | extensiones.append(("ficheros xml", "*.xml")) 54 | if extension_html.get(): 55 | extensiones.append(("ficheros html", "*.html")) 56 | 57 | def salir(): 58 | root.destroy() 59 | 60 | #Ventana principal 61 | root = Tk() 62 | root.title("Editor de texto") 63 | 64 | #Variables de control 65 | extension_xml = IntVar() 66 | extension_html = IntVar() 67 | 68 | #Creación de widgets de la ventana principal 69 | barra_menus = Menu() 70 | area_texto = Text(padx=10, pady=10, bd=5) 71 | 72 | #Menú Archivo 73 | menu_archivo = Menu(tearoff=0) 74 | menu_archivo.add_command(label="Nuevo", command=nuevo) 75 | 76 | submenu_abrir = Menu(tearoff=0) 77 | submenu_abrir.add_command(label="Explorar", command=abrir) 78 | submenu_abrir.add_command(label="Recientes") 79 | menu_archivo.add_cascade(label='Abrir', menu=submenu_abrir) 80 | 81 | menu_archivo.add_command(label="Guardar", command=guardar) 82 | menu_archivo.add_command(label="Guardar como", command=guardar_como) 83 | menu_archivo.add_separator() 84 | 85 | submenu_extensiones = Menu(tearoff=False) 86 | submenu_extensiones.add_checkbutton(label="xml", variable=extension_xml, command=gestion_extensiones) 87 | submenu_extensiones.add_checkbutton(label="html", variable=extension_html, command=gestion_extensiones) 88 | menu_archivo.add_cascade(label='Extensiones', menu=submenu_extensiones) 89 | 90 | menu_archivo.add_separator() 91 | img = PhotoImage(file="../imagenes/salir.gif") 92 | menu_archivo.add_command(label="Salir", image=img, compound="left", command=salir) 93 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 94 | 95 | #Menú edición 96 | menu_edicion = Menu(tearoff=0) 97 | menu_edicion.add_command(label="Deshacer") 98 | menu_edicion.add_command(label="Rehacer") 99 | menu_edicion.add_separator() 100 | menu_edicion.add_command(label="Copiar") 101 | menu_edicion.add_command(label="Pegar") 102 | menu_edicion.add_command(label="Borrar") 103 | menu_edicion.add_command(label="Seleccionar todo") 104 | barra_menus.add_cascade(label="Edición", menu=menu_edicion) 105 | 106 | #Menú ayuda 107 | menu_ayuda = Menu(tearoff=0) 108 | menu_ayuda.add_command(label="Manual de usuario") 109 | menu_ayuda.add_command(label="Acerca de...") 110 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 111 | 112 | #Composición de los widgets de la ventana principal 113 | root.config(menu=barra_menus) 114 | area_texto.pack(expand= True, fill="both") 115 | 116 | root.mainloop() 117 | 118 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/checkbutton_radiobutton_formulario.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Button, Entry, Spinbox, OptionMenu, IntVar, StringVar, Radiobutton, Checkbutton, Frame, messagebox 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | 6 | ################################################### 7 | #Funciones que se ejecutan al pulsar los botones 8 | ################################################### 9 | def aceptar(): 10 | selecciones=nombre=direccion=provincia=edad=sexo=aficiones="" 11 | 12 | nombre = nombre_entry.get() 13 | direccion = direccion_entry.get() 14 | provincia = var_provincia.get() 15 | edad = edad_entry.get() 16 | sexo = radio_var.get() 17 | aficion1 = check_var1.get() 18 | aficion2 = check_var2.get() 19 | aficion3 = check_var3.get() 20 | if aficion1: aficiones += "Música " 21 | if aficion2: aficiones += "Deporte " 22 | if aficion3: aficiones += "Lectura" 23 | 24 | if nombre:selecciones = "Nombre : "+nombre+"\n" 25 | if direccion:selecciones += "Dirección : "+direccion+"\n" 26 | if provincia != "Pulse para ver las permitidas": 27 | selecciones += "Provincia: "+provincia+"\n" 28 | selecciones += "Edad: "+edad+"\n" 29 | selecciones += "Sexo: "+sexo+"\n" 30 | if aficiones:selecciones += "Aficiones: "+aficiones+"\n" 31 | 32 | messagebox.showinfo("Selección", selecciones) 33 | 34 | def cancelar(): 35 | nombre_entry.delete(0, "end") 36 | direccion_entry.delete(0, "end") 37 | var_provincia.set("Pulse para ver las permitidas") 38 | edad_entry.delete(0, "end") 39 | edad_entry.insert(0, edad_minima) 40 | hombre_radiobutton.select() 41 | aficion1_checkbutton.deselect() 42 | aficion2_checkbutton.deselect() 43 | aficion3_checkbutton.deselect() 44 | 45 | #Ventana principal 46 | root = Tk() 47 | root.title("Formulario") 48 | root.resizable(True, False) 49 | root.minsize(300, 100) 50 | 51 | 52 | #Variables de control 53 | var_provincia = StringVar() 54 | radio_var = StringVar() 55 | check_var1 = IntVar() 56 | check_var2 = IntVar() 57 | check_var3 = IntVar() 58 | 59 | ################################################### 60 | #Creación de widgets 61 | ################################################### 62 | 63 | #Creación de la etiqueta y el campo del nombre 64 | nombre_label = Label(text="Nombre:") 65 | nombre_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 66 | 67 | #Creación de la etiqueta y el campo de la dirección 68 | direccion_label = Label(text="Dirección:") 69 | direccion_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 70 | 71 | #Creación de la etiqueta y el campo de la provincia 72 | provincia_label = Label(text="Provincia:") 73 | provincia_menu = OptionMenu(root, var_provincia, "León", "Zamora", "Salamanca", "Valladolid", "Palencia") 74 | var_provincia.set("Pulse para ver las permitidas") 75 | 76 | #Creación de la etiqueta y el campo de la edad 77 | edad_label = Label(text="Edad:") 78 | edad_entry = Spinbox(from_=edad_minima, to=edad_maxima, width=3, bd=5, highlightcolor="red", highlightthickness=2) 79 | 80 | #Creación de la etiqueta, los radiobuttons de sexo y el frame que los contiene 81 | sexo_label = Label(text="Sexo:") 82 | frame_radiobuttons = Frame() 83 | hombre_radiobutton = Radiobutton(frame_radiobuttons, text="Hombre", variable=radio_var, value="Hombre") 84 | mujer_radiobutton = Radiobutton(frame_radiobuttons, text="Mujer", variable=radio_var, value="Mujer") 85 | 86 | #Creación de la etiqueta, los radiobuttons de las aficiones y el frame que los contiene 87 | aficiones_label = Label(text="Aficiones:") 88 | frame_checkbuttons = Frame() 89 | aficion1_checkbutton = Checkbutton(frame_checkbuttons, text = "Música", variable = check_var1) 90 | aficion2_checkbutton = Checkbutton(frame_checkbuttons, text = "Deporte", variable = check_var2) 91 | aficion3_checkbutton = Checkbutton(frame_checkbuttons, text = "Lectura", variable = check_var3) 92 | 93 | #creación de los botones 94 | boton_aceptar = Button(text="ACEPTAR", command=aceptar) 95 | boton_cancelar = Button(text="CANCELAR", command=cancelar) 96 | 97 | ################################################### 98 | #Composición de los widgets en la interfaz 99 | ################################################### 100 | 101 | #Composición de los widgets del nombre 102 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 103 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 104 | 105 | #Composición de los widgets de la dirección 106 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 107 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 108 | 109 | #Composición de los widgets de la provincia 110 | provincia_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 111 | provincia_menu.grid(row=2, column=1, sticky= "w", padx=10) 112 | 113 | #Composición de los widgets de la edad 114 | edad_label.grid(row=3, column=0, sticky= "w", padx=10, pady=10) 115 | edad_entry.grid(row=3, column=1, sticky= "w", padx=10) 116 | 117 | #Permite que los campos de entrada de texto crezcan a lo ancho con la ventana 118 | root.columnconfigure(1, weight=1) 119 | 120 | #Composición de los widgets del sexo 121 | sexo_label.grid(row=4, column=0, sticky= "w", padx=10, pady=10) 122 | frame_radiobuttons.grid(row=4, column=1, sticky= "w", padx=10, pady=10) 123 | hombre_radiobutton.pack(side= "left") 124 | mujer_radiobutton.pack(side= "left") 125 | hombre_radiobutton.select() 126 | 127 | #Composición de los widgets de las aficiones 128 | aficiones_label.grid(row=5, column=0, sticky= "w", padx=10, pady=10) 129 | frame_checkbuttons.grid(row=5, column=1, sticky= "w", padx=10, pady=10) 130 | aficion1_checkbutton.pack(side= "left") 131 | aficion2_checkbutton.pack(side= "left") 132 | aficion3_checkbutton.pack(side= "left") 133 | 134 | #Composición de los widgets de los botones 135 | boton_aceptar.grid(row=6, column=0, padx=10, pady=10, sticky= "W") 136 | boton_cancelar.grid(row=6, column=1, padx=10, pady=10, sticky= "E") 137 | 138 | root.mainloop() 139 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/colorchooser.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Button, colorchooser 2 | 3 | def elegir_color(): 4 | color = colorchooser.askcolor(title ="Elige un color") 5 | boton.configure(bg=color[1]) 6 | 7 | root = Tk() 8 | root.minsize(False, False) 9 | 10 | boton = Button(text = "Selecciona un color", font=("Arial", "24", "bold"), fg="blue", bd=5, command = elegir_color) 11 | boton.pack(padx=50, pady=50) 12 | 13 | 14 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/entry.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Button, Entry 2 | 3 | def aceptar(): 4 | root.destroy() 5 | 6 | def cancelar(): 7 | usuario_entry.delete(0, "end") 8 | contraseña_entry.delete(0, "end") 9 | 10 | root = Tk() 11 | root.title("Login") 12 | root.resizable(False, False) 13 | 14 | usuario_label = Label(text="USUARIO:") 15 | usuario_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 16 | contraseña_label = Label(text="CONTRASEÑA:") 17 | contraseña_entry = Entry(bd=5, show='*', highlightcolor="red", highlightthickness=2) 18 | boton_aceptar = Button(text="ACEPTAR", command=aceptar) 19 | boton_cancelar = Button(text="CANCELAR", command=cancelar) 20 | 21 | usuario_label.grid(row=0, column=0, sticky= "W", padx=10, pady=10) 22 | usuario_entry.grid(row=0, column=1, sticky= "E", padx=10) 23 | contraseña_label.grid(row=1, column=0, sticky= "W", padx=10, pady=10) 24 | contraseña_entry.grid(row=1, column=1, sticky= "E", padx=10) 25 | boton_aceptar.grid(row=2, column=0, padx=10, pady=10, sticky= "W") 26 | boton_cancelar.grid(row=2, column=1, padx=10, pady=10, sticky= "E") 27 | 28 | root.mainloop() 29 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/frames.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Text, Button, Frame 2 | 3 | root = Tk() 4 | root.title("Frames") 5 | root.minsize(400, 200) 6 | 7 | frame_izquierdo = Frame(root) 8 | frame_derecho = Frame(root) 9 | frame_inferior = Frame(root) 10 | 11 | frame_izquierdo.grid(row=0, column=0, sticky="nsew") 12 | root.rowconfigure(0, weight=1) 13 | root.columnconfigure(0, weight=1) 14 | 15 | frame_derecho.grid(row=0, column=1, sticky="n", padx=5) 16 | frame_inferior.grid(row=1, column=0, columnspan=2, sticky="ew", padx=5, pady=5) 17 | 18 | area_texto = Text(frame_izquierdo, padx=10, pady=10, bd=5) 19 | area_texto.pack(expand= True, fill="both") 20 | 21 | boton_nuevo = Button(frame_derecho, text=" NUEVO ") 22 | boton_abrir = Button(frame_derecho, text=" ABRIR ") 23 | boton_guardar = Button(frame_derecho, text="GUARDAR") 24 | boton_nuevo.pack(pady=5) 25 | boton_abrir.pack() 26 | boton_guardar.pack(pady=5) 27 | 28 | boton_ayuda = Button(frame_inferior, text=" AYUDA ") 29 | boton_salir = Button(frame_inferior, text=" SALIR ", width=8) 30 | boton_ayuda.pack(side="left") 31 | boton_salir.pack(side="right") 32 | 33 | root.mainloop() 34 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/label_reloj.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, StringVar 2 | import time 3 | 4 | def actualizar_hora(): 5 | hora = time.strftime("%H:%M:%S") 6 | variable_control.set(hora) 7 | root.after(1000, actualizar_hora) 8 | 9 | root = Tk() 10 | root.resizable(False, False) 11 | 12 | variable_control = StringVar() 13 | 14 | reloj = Label(textvariable= variable_control, fg="red", font=("Arial", 18), padx=20, pady=20, bitmap="hourglass", compound="left") 15 | #reloj = Label(textvariable= variable_control, fg="red", font=("Arial", 18), padx=20, pady=20) 16 | reloj.pack() 17 | 18 | actualizar_hora() 19 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/listbox.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Button, Label, Listbox, StringVar 2 | 3 | def traducir(): 4 | entrada = lista_idiomas.curselection() 5 | if entrada != (): 6 | idioma = lista_idiomas.get(entrada) 7 | if idioma == "Inglés": traduccion = "Hi there" 8 | elif idioma == "Francés": traduccion = "Salut" 9 | elif idioma == "Italiano": traduccion = "Ciao" 10 | elif idioma == "Alemán": traduccion = "Hallo" 11 | palabra_traducida.configure(text=traduccion) 12 | 13 | root = Tk() 14 | root.resizable(False, False) 15 | 16 | var_control_idiomas = StringVar(value="Inglés Francés Italiano Alemán") 17 | 18 | palabra_original = Label(text="Hola", font=("Arial", 12, "bold italic")) 19 | boton = Button(text="-->", command=traducir) 20 | palabra_traducida = Label(text="¿?", font=("Arial", 12, "bold italic")) 21 | lista_idiomas = Listbox(listvariable=var_control_idiomas, height=4, bd=3) 22 | 23 | 24 | palabra_original.grid(row=0, column=0, padx= 5, pady=5) 25 | boton.grid(row=0, column=1, padx= 5, pady=5) 26 | palabra_traducida.grid(row=0, column=2, padx= 5, pady=5) 27 | lista_idiomas.grid(row=1, column=1, pady=5) 28 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/menu.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Menu, PhotoImage 2 | 3 | def salir(): 4 | root.destroy() 5 | 6 | root = Tk() 7 | barra_menus = Menu() 8 | root.config(menu=barra_menus) 9 | 10 | menu_archivo = Menu(tearoff=0) 11 | menu_archivo.add_command(label="Nuevo") 12 | 13 | submenu_abrir = Menu(tearoff=0) 14 | submenu_abrir.add_command(label="Explorar") 15 | submenu_abrir.add_command(label="Recientes") 16 | menu_archivo.add_cascade(label='Abrir', menu=submenu_abrir) 17 | 18 | menu_archivo.add_command(label="Guardar") 19 | menu_archivo.add_command(label="Guardar como") 20 | menu_archivo.add_separator() 21 | img = PhotoImage(file="../imagenes/salir.gif") 22 | menu_archivo.add_command(label="Salir", image=img, compound="left", command=salir) 23 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 24 | 25 | menu_edicion = Menu(tearoff=0) 26 | menu_edicion.add_command(label="Deshacer") 27 | menu_edicion.add_command(label="Rehacer") 28 | menu_edicion.add_separator() 29 | menu_edicion.add_command(label="Copiar") 30 | menu_edicion.add_command(label="Pegar") 31 | menu_edicion.add_command(label="Borrar") 32 | menu_edicion.add_command(label="Seleccionar todo") 33 | barra_menus.add_cascade(label="Edición", menu=menu_edicion) 34 | 35 | 36 | menu_ayuda = Menu(tearoff=0) 37 | menu_ayuda.add_command(label="Manual usuario") 38 | menu_ayuda.add_command(label="Acerca de...") 39 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 40 | 41 | root.mainloop() 42 | 43 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/menubutton.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Button, Entry, Spinbox, OptionMenu, Menu, Menubutton, StringVar 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | 6 | def aceptar(): 7 | selecciones = "" 8 | 9 | nombre = nombre_entry.get() 10 | direccion = direccion_entry.get() 11 | provincia = var_provincia.get() 12 | edad = edad_entry.get() 13 | sexo = sexo_var.get() 14 | if nombre:selecciones = "Nombre: "+nombre+"\n" 15 | if direccion:selecciones += "Dirección: "+direccion+"\n" 16 | if provincia != "Pulse para ver las permitidas": 17 | selecciones += "Provincia: "+provincia+"\n" 18 | selecciones += "Edad: "+edad+"\n" 19 | if sexo != "Pulse sobre \"Sexo\"": 20 | selecciones += "Sexo: "+sexo+"\n" 21 | selecciones_label.config(text=selecciones) 22 | 23 | def cancelar(): 24 | nombre_entry.delete(0, "end") 25 | direccion_entry.delete(0, "end") 26 | var_provincia.set("Pulse para ver las permitidas") 27 | edad_entry.delete(0, "end") 28 | edad_entry.insert(0, 18) 29 | sexo_var.set("Pulse sobre \"Sexo\"") 30 | selecciones_label.config(text="") 31 | 32 | def es_hombre(): 33 | sexo_var.set("Hombre") 34 | 35 | def es_mujer(): 36 | sexo_var.set("Mujer") 37 | 38 | root = Tk() 39 | root.title("Formulario") 40 | root.resizable(True, False) 41 | root.minsize(300, 100) 42 | 43 | var_provincia = StringVar() 44 | sexo_var = StringVar() 45 | 46 | nombre_label = Label(text="Nombre:") 47 | nombre_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 48 | direccion_label = Label(text="Dirección:") 49 | direccion_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 50 | provincia_label = Label(text="Provincia:") 51 | provincia_menu = OptionMenu(root, var_provincia, "León", "Zamora", "Salamanca", "Valladolid", "Palencia") 52 | var_provincia.set("Pulse para ver las permitidas") 53 | edad_label = Label(text="Edad:") 54 | edad_entry = Spinbox(from_=edad_minima, to=edad_maxima, width=3, bd=5, highlightcolor="red", highlightthickness=2) 55 | 56 | sexo_entry = Entry(bd=5, state="disabled", textvariable=sexo_var) 57 | sexo_var.set("Pulse sobre \"Sexo\"") 58 | sexo_menu = Menubutton(text = "Sexo:", relief="raised") 59 | sexo_menu.menu = Menu(sexo_menu, tearoff=0) 60 | sexo_menu.menu.add_command(label="Hombre", command=es_hombre) 61 | sexo_menu.menu.add_command(label="Mujer", command=es_mujer) 62 | sexo_menu["menu"]= sexo_menu.menu 63 | 64 | selecciones_label = Label(text="", padx=10, justify="left") 65 | boton_aceptar = Button(text="ACEPTAR", command=aceptar) 66 | boton_cancelar = Button(text="CANCELAR", command=cancelar) 67 | 68 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 69 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 70 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 71 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 72 | provincia_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 73 | provincia_menu.grid(row=2, column=1, sticky= "w", padx=10) 74 | edad_label.grid(row=3, column=0, sticky= "w", padx=10, pady=10) 75 | edad_entry.grid(row=3, column=1, sticky= "w", padx=10) 76 | sexo_menu.grid(row=4, column=0, sticky= "w", padx=10, pady=10) 77 | sexo_entry.grid(row=4, column=1, sticky= "w", padx=10) 78 | 79 | root.columnconfigure(1, weight=1) 80 | 81 | selecciones_label.grid(row=5, column=0, columnspan=2, sticky= "W") 82 | boton_aceptar.grid(row=6, column=0, padx=10, pady=10, sticky= "W") 83 | boton_cancelar.grid(row=6, column=1, padx=10, pady=10, sticky= "E") 84 | 85 | root.mainloop() 86 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/messagebox.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Menu, PhotoImage, messagebox 2 | 3 | def salir(): 4 | root.destroy() 5 | 6 | def manual_usuario(): 7 | messagebox.showinfo("Manual de usuario", "En construcción...") 8 | 9 | def acerca_de(): 10 | messagebox.showinfo("Acerca de...", "Versión 1.0") 11 | 12 | root = Tk() 13 | barra_menus = Menu() 14 | root.config(menu=barra_menus) 15 | 16 | menu_archivo = Menu(tearoff=0) 17 | menu_archivo.add_command(label="Nuevo") 18 | 19 | submenu_abrir = Menu(tearoff=0) 20 | submenu_abrir.add_command(label="Explorar") 21 | submenu_abrir.add_command(label="Recientes") 22 | menu_archivo.add_cascade(label='Abrir', menu=submenu_abrir) 23 | 24 | menu_archivo.add_command(label="Guardar") 25 | menu_archivo.add_command(label="Guardar como") 26 | menu_archivo.add_separator() 27 | img = PhotoImage(file="../imagenes/salir.gif") 28 | menu_archivo.add_command(label="Salir", image=img, compound="left", command=salir) 29 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 30 | 31 | menu_edicion = Menu(tearoff=0) 32 | menu_edicion.add_command(label="Deshacer") 33 | menu_edicion.add_command(label="Rehacer") 34 | menu_edicion.add_separator() 35 | menu_edicion.add_command(label="Copiar") 36 | menu_edicion.add_command(label="Pegar") 37 | menu_edicion.add_command(label="Borrar") 38 | menu_edicion.add_command(label="Seleccionar todo") 39 | barra_menus.add_cascade(label="Edición", menu=menu_edicion) 40 | 41 | 42 | menu_ayuda = Menu(tearoff=0) 43 | menu_ayuda.add_command(label="Manual de usuario", command=manual_usuario) 44 | menu_ayuda.add_command(label="Acerca de...", command=acerca_de) 45 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 46 | 47 | root.mainloop() 48 | 49 | 50 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/optionmenu.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Button, Entry, Spinbox, OptionMenu, StringVar 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | 6 | def aceptar(): 7 | selecciones = "" 8 | 9 | nombre = nombre_entry.get() 10 | direccion = direccion_entry.get() 11 | provincia = var_provincia.get() 12 | edad = edad_entry.get() 13 | if nombre:selecciones = "Nombre : "+nombre+"\n" 14 | if direccion:selecciones += "Dirección : "+direccion+"\n" 15 | if provincia != "Pulse para ver las permitidas": 16 | selecciones += "Provincia : "+provincia+"\n" 17 | selecciones += "Edad: "+edad 18 | selecciones_label.config(text=selecciones) 19 | 20 | def cancelar(): 21 | nombre_entry.delete(0, "end") 22 | direccion_entry.delete(0, "end") 23 | var_provincia.set("Pulse para ver las permitidas") 24 | edad_entry.delete(0, "end") 25 | edad_entry.insert(0, 18) 26 | selecciones_label.config(text="") 27 | 28 | root = Tk() 29 | root.title("Formulario") 30 | root.resizable(True, False) 31 | root.minsize(300, 100) 32 | 33 | var_provincia = StringVar() 34 | 35 | nombre_label = Label(text="Nombre:") 36 | nombre_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 37 | direccion_label = Label(text="Dirección:") 38 | direccion_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 39 | provincia_label = Label(text="Provincia:") 40 | provincia_menu = OptionMenu(root, var_provincia, "León", "Zamora", "Salamanca", "Valladolid", "Palencia") 41 | var_provincia.set("Pulse para ver las permitidas") 42 | edad_label = Label(text="Edad:") 43 | edad_entry = Spinbox(from_=edad_minima, to=edad_maxima, width=3, bd=5, highlightcolor="red", highlightthickness=2) 44 | selecciones_label = Label(text="", padx=10, justify="left") 45 | boton_aceptar = Button(text="ACEPTAR", command=aceptar) 46 | boton_cancelar = Button(text="CANCELAR", command=cancelar) 47 | 48 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 49 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 50 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 51 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 52 | provincia_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 53 | provincia_menu.grid(row=2, column=1, sticky= "w", padx=10) 54 | edad_label.grid(row=3, column=0, sticky= "w", padx=10, pady=10) 55 | edad_entry.grid(row=3, column=1, sticky= "w", padx=10) 56 | 57 | root.columnconfigure(1, weight=1) 58 | 59 | selecciones_label.grid(row=4, column=0, columnspan=2, sticky= "W") 60 | boton_aceptar.grid(row=5, column=0, padx=10, pady=10, sticky= "W") 61 | boton_cancelar.grid(row=5, column=1, padx=10, pady=10, sticky= "E") 62 | 63 | root.mainloop() 64 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/panedwindow.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Text, LabelFrame, PanedWindow, RAISED, BOTH, VERTICAL, NE 2 | 3 | root = Tk() 4 | root.title("Paneles") 5 | root.minsize(800, 400) 6 | 7 | cabecera = Label(text="Editores de texto", pady=10, fg="blue", font=("Arial", "24", "bold")) 8 | cabecera.pack() 9 | 10 | root_panel = PanedWindow(sashrelief = RAISED) 11 | root_panel.pack(fill=BOTH, expand=True) 12 | 13 | frame_izquierdo = LabelFrame(root_panel, text=" Editor izquierdo ", font=("Arial", "12")) 14 | text_izquierdo = Text(frame_izquierdo, padx=10, pady=10, bd=5, width=50) 15 | text_izquierdo.pack(fill=BOTH, expand=True) 16 | root_panel.add(frame_izquierdo) 17 | 18 | subpanel_derecho = PanedWindow(root_panel, orient=VERTICAL, showhandle= True) 19 | root_panel.add(subpanel_derecho) 20 | 21 | frame_superior = LabelFrame(root_panel, text=" Editor derecho superior ", font=("Arial", "12"), labelanchor=NE) 22 | text_superior = Text(frame_superior, padx=10, pady=10, bd=5, width=50, height=10) 23 | text_superior.pack(fill=BOTH, expand=True) 24 | subpanel_derecho.add(frame_superior) 25 | 26 | frame_inferior = LabelFrame(root_panel, text=" Editor derecho inferior ", font=("Arial", "12"), labelanchor=NE) 27 | text_inferior = area_texto = Text(frame_inferior, padx=10, pady=10, bd=5, width=50, height=10) 28 | text_inferior.pack(fill=BOTH, expand=True) 29 | subpanel_derecho.add(frame_inferior) 30 | 31 | root.mainloop() 32 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/scale_arco.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas, Scale 2 | 3 | ancho = 400 4 | alto = 200 5 | radio = 75 6 | 7 | def modifica_arco(angulo): 8 | canvas.itemconfig(arco, extent=angulo) 9 | 10 | root = Tk() 11 | root.title("Arco") 12 | root.resizable(False, False) 13 | 14 | canvas = Canvas(width=ancho, height=alto) 15 | arco = canvas.create_arc(ancho/2-radio, alto/2-radio, ancho/2+radio, alto/2+radio, start=0, extent=0, fill="blue", outline="") 16 | barra_deslizamiento = Scale(label='ÁNGULO', from_=0, to=360, orient="horizontal", length=ancho, command=modifica_arco, tickinterval=90) 17 | 18 | canvas.pack() 19 | barra_deslizamiento.pack() 20 | 21 | root.mainloop() 22 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/scroll.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Menu, Text, PhotoImage, filedialog, Scrollbar 2 | 3 | fichero="" 4 | 5 | ########################################################## 6 | #Funciones que se ejecutan seleccionar una opción del menú 7 | ########################################################## 8 | 9 | def nuevo(): 10 | global fichero 11 | 12 | area_texto.delete(1.0, "end") 13 | fichero = "" 14 | 15 | def abrir(): 16 | global fichero 17 | 18 | fichero = filedialog.askopenfilename(initialdir = ".", title = "Abrir archivo", filetypes = [("ficheros texto", "*.txt")]) 19 | if fichero: 20 | f = open(fichero, "r", encoding='utf-8') 21 | area_texto.delete(1.0, "end") 22 | area_texto.insert("insert", f.read()) 23 | f.close() 24 | 25 | def guardar(): 26 | global fichero 27 | if not(fichero): fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 28 | if fichero: 29 | texto = area_texto.get(1.0, "end") 30 | f = open(fichero, "w", encoding='utf-8') 31 | f.write(texto) 32 | f.close 33 | 34 | def guardar_como(): 35 | global fichero 36 | 37 | fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar como", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 38 | if fichero: 39 | texto = area_texto.get(1.0, "end") 40 | f = open(fichero, "w", encoding='utf-8') 41 | f.write(texto) 42 | f.close 43 | 44 | def salir(): 45 | root.destroy() 46 | 47 | #Ventana principal 48 | root = Tk() 49 | root.title("Editor de texto") 50 | 51 | #Creación de widgets de la ventana principal 52 | barra_menus = Menu() 53 | area_texto = Text(padx=10, pady=10, bd=5) 54 | scrollbar = Scrollbar(command=area_texto.yview) 55 | area_texto.config(yscrollcommand = scrollbar.set) 56 | 57 | #Menú Archivo 58 | menu_archivo = Menu(tearoff=0) 59 | menu_archivo.add_command(label="Nuevo", command=nuevo) 60 | 61 | submenu_abrir = Menu(tearoff=0) 62 | submenu_abrir.add_command(label="Archivo", command=abrir) 63 | submenu_abrir.add_command(label="Recientes") 64 | menu_archivo.add_cascade(label='Abrir', menu=submenu_abrir) 65 | 66 | menu_archivo.add_command(label="Guardar", command=guardar) 67 | menu_archivo.add_command(label="Guardar como", command=guardar_como) 68 | menu_archivo.add_separator() 69 | img = PhotoImage(file="../imagenes/salir.gif") 70 | menu_archivo.add_command(label="Salir", image=img, compound="left", command=salir) 71 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 72 | 73 | #Menú edición 74 | menu_edicion = Menu(tearoff=0) 75 | menu_edicion.add_command(label="Deshacer") 76 | menu_edicion.add_command(label="Rehacer") 77 | menu_edicion.add_separator() 78 | menu_edicion.add_command(label="Copiar") 79 | menu_edicion.add_command(label="Pegar") 80 | menu_edicion.add_command(label="Borrar") 81 | menu_edicion.add_command(label="Seleccionar todo") 82 | barra_menus.add_cascade(label="Edición", menu=menu_edicion) 83 | 84 | #Menú ayuda 85 | menu_ayuda = Menu(tearoff=0) 86 | menu_ayuda.add_command(label="Manual de usuario") 87 | menu_ayuda.add_command(label="About...") 88 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 89 | 90 | #Composición de los widgets de la ventana principal 91 | root.config(menu=barra_menus) 92 | area_texto.pack(expand=True, fill="both", side = "left") 93 | scrollbar.pack(side = "right", fill = "y") 94 | 95 | root.mainloop() 96 | 97 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/spinbox.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Entry, Spinbox, Button 2 | 3 | edad_minima = 18 4 | edad_maxima = 65 5 | 6 | def aceptar(): 7 | selecciones = "" 8 | 9 | nombre = nombre_entry.get() 10 | direccion = direccion_entry.get() 11 | edad = edad_entry.get() 12 | if nombre:selecciones = "Nombre : "+nombre+"\n" 13 | if direccion:selecciones += "Dirección : "+direccion+"\n" 14 | selecciones += "Edad: "+edad 15 | selecciones_label.config(text=selecciones) 16 | 17 | def cancelar(): 18 | nombre_entry.delete(0, "end") 19 | direccion_entry.delete(0, "end") 20 | edad_entry.delete(0, "end") 21 | edad_entry.insert(0, 18) 22 | selecciones_label.config(text="") 23 | 24 | root = Tk() 25 | root.title("Formulario") 26 | root.resizable(True, False) 27 | root.minsize(300, 100) 28 | 29 | nombre_label = Label(text="Nombre:") 30 | nombre_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 31 | direccion_label = Label(text="Dirección:") 32 | direccion_entry = Entry(bd=5, highlightcolor="red", highlightthickness=2) 33 | edad_label = Label(text="Edad:") 34 | edad_entry = Spinbox(from_=edad_minima, to=edad_maxima, width=3, bd=5, highlightcolor="red", highlightthickness=2) 35 | selecciones_label = Label(text="", padx=10, justify="left") 36 | boton_aceptar = Button(text="ACEPTAR", command=aceptar) 37 | boton_cancelar = Button(text="CANCELAR", command=cancelar) 38 | 39 | nombre_label.grid(row=0, column=0, sticky= "w", padx=10, pady=10) 40 | nombre_entry.grid(row=0, column=1, sticky= "ew", padx=10) 41 | direccion_label.grid(row=1, column=0, sticky= "w", padx=10, pady=10) 42 | direccion_entry.grid(row=1, column=1, sticky= "ew", padx=10) 43 | edad_label.grid(row=2, column=0, sticky= "w", padx=10, pady=10) 44 | edad_entry.grid(row=2, column=1, sticky= "w", padx=10) 45 | 46 | root.columnconfigure(1, weight=1) 47 | 48 | selecciones_label.grid(row=3, column=0, columnspan=2, sticky= "W") 49 | boton_aceptar.grid(row=4, column=0, padx=10, pady=10, sticky= "W") 50 | boton_cancelar.grid(row=4, column=1, padx=10, pady=10, sticky= "E") 51 | 52 | root.mainloop() 53 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/text.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Menu, Text, PhotoImage, filedialog 2 | 3 | fichero="" 4 | 5 | ########################################################## 6 | #Funciones que se ejecutan seleccionar una opción del menú 7 | ########################################################## 8 | 9 | def nuevo(): 10 | global fichero 11 | 12 | area_texto.delete(1.0, "end") 13 | fichero = "" 14 | 15 | def abrir(): 16 | global fichero 17 | 18 | fichero = filedialog.askopenfilename(initialdir = ".", title = "Abrir archivo", filetypes = [("ficheros texto", "*.txt")]) 19 | if fichero: 20 | f = open(fichero, "r", encoding='utf-8') 21 | area_texto.delete(1.0, "end") 22 | area_texto.insert(1.0, f.read()) 23 | f.close() 24 | 25 | def guardar(): 26 | global fichero 27 | if not(fichero): fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 28 | if fichero: 29 | texto = area_texto.get(1.0, "end") 30 | f = open(fichero, "w", encoding='utf-8') 31 | f.write(texto) 32 | f.close 33 | 34 | def guardar_como(): 35 | global fichero 36 | 37 | fichero = filedialog.asksaveasfilename(initialdir = ".", title = "Guardar como", filetypes = [("ficheros texto", "*.txt")], defaultextension=".txt") 38 | if fichero: 39 | texto = area_texto.get(1.0, "end") 40 | f = open(fichero, "w", encoding='utf-8') 41 | f.write(texto) 42 | f.close 43 | 44 | def salir(): 45 | root.destroy() 46 | 47 | #Ventana principal 48 | root = Tk() 49 | root.title("Editor de texto") 50 | 51 | #Creación de widgets de la ventana principal 52 | barra_menus = Menu() 53 | area_texto = Text(padx=10, pady=10, bd=5) 54 | area_texto.tag_configure("sel", background="yellow", foreground="blue") 55 | 56 | #Menú Archivo 57 | menu_archivo = Menu(tearoff=0) 58 | menu_archivo.add_command(label="Nuevo", command=nuevo) 59 | 60 | submenu_abrir = Menu(tearoff=0) 61 | submenu_abrir.add_command(label="Explorar", command=abrir) 62 | submenu_abrir.add_command(label="Recientes") 63 | menu_archivo.add_cascade(label='Abrir', menu=submenu_abrir) 64 | 65 | menu_archivo.add_command(label="Guardar", command=guardar) 66 | menu_archivo.add_command(label="Guardar como", command=guardar_como) 67 | menu_archivo.add_separator() 68 | img = PhotoImage(file="../imagenes/salir.gif") 69 | menu_archivo.add_command(label="Salir", image=img, compound="left", command=salir) 70 | barra_menus.add_cascade(label="Archivo", menu=menu_archivo) 71 | 72 | #Menú edición 73 | menu_edicion = Menu(tearoff=0) 74 | menu_edicion.add_command(label="Deshacer") 75 | menu_edicion.add_command(label="Rehacer") 76 | menu_edicion.add_separator() 77 | menu_edicion.add_command(label="Copiar") 78 | menu_edicion.add_command(label="Pegar") 79 | menu_edicion.add_command(label="Borrar") 80 | menu_edicion.add_command(label="Seleccionar todo") 81 | barra_menus.add_cascade(label="Edición", menu=menu_edicion) 82 | 83 | #Menú ayuda 84 | menu_ayuda = Menu(tearoff=0) 85 | menu_ayuda.add_command(label="Manual de usuario") 86 | menu_ayuda.add_command(label="Acerca de...") 87 | barra_menus.add_cascade(label="Ayuda", menu=menu_ayuda) 88 | 89 | #Composición de los widgets de la ventana principal 90 | root.config(menu=barra_menus) 91 | area_texto.pack(expand= True, fill="both") 92 | 93 | root.mainloop() 94 | 95 | -------------------------------------------------------------------------------- /Codigo/Tkinter/widgets/toplevel.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Label, Button, Entry, Toplevel 2 | 3 | def aceptar(): 4 | usuario = usuario_entry.get() 5 | if usuario: 6 | etiqueta.configure(text="Usuario: " + usuario) 7 | else: 8 | etiqueta.configure(text="Usuario no introducido") 9 | ventana_acceso.destroy() 10 | 11 | def cancelar(): 12 | usuario_entry.delete(0, "end") 13 | contraseña_entry.delete(0, "end") 14 | 15 | def acceder(): 16 | global ventana_acceso, usuario_entry, contraseña_entry 17 | 18 | ventana_acceso = Toplevel() 19 | ventana_acceso.title("Login") 20 | ventana_acceso.resizable(False, False) 21 | 22 | usuario_label = Label(ventana_acceso, text="USUARIO:") 23 | usuario_entry = Entry(ventana_acceso, bd=5, highlightcolor="red", highlightthickness=2) 24 | contraseña_label = Label(ventana_acceso, text="CONTRASEÑA:") 25 | contraseña_entry = Entry(ventana_acceso, bd=5, show='*', highlightcolor="red", highlightthickness=2) 26 | boton_aceptar = Button(ventana_acceso, text="ACEPTAR", command=aceptar) 27 | boton_cancelar = Button(ventana_acceso, text="CANCELAR", command=cancelar) 28 | 29 | usuario_label.grid(row=0, column=0, sticky= "W", padx=10, pady=10) 30 | usuario_entry.grid(row=0, column=1, padx=10) 31 | contraseña_label.grid(row=1, column=0, sticky= "W", padx=10, pady=10) 32 | contraseña_entry.grid(row=1, column=1, padx=10) 33 | boton_aceptar.grid(row=2, column=0, padx=10, pady=10, sticky= "W") 34 | boton_cancelar.grid(row=2, column=1, padx=10, pady=10, sticky= "E") 35 | 36 | root = Tk() 37 | root.title("Ventana de acceso") 38 | root.geometry("300x150") 39 | root.minsize(300, 150) 40 | boton = Button(text="ACCEDER",command=acceder) 41 | etiqueta = Label(text="Usuario no introducido") 42 | boton.place(relx=0.5, rely=0.5, anchor="center") 43 | etiqueta.pack(side="bottom", pady=5) 44 | 45 | root.mainloop() 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # desarrollo-de-interficies-graficas-python-tkinter 2 | Libro de desarrollo de interfaces graficas en python 3 con tkinter 3 | --------------------------------------------------------------------------------