~/blog/reloj-digital-con-python

Código Completo

·2 min read·

Importar módulos:

  • tkinter
    • El módulo tkinter se usa para crear interfaces gráficas.
    • El módulo ttk se usa para crear interfaces gráficas.
  • time
    • El módulo time se usa para obtener la hora.
    • El módulo strftime se usa para formatear la hora.
from tkinter import * 
from tkinter.ttk import * 
from time import strftime

Configuramos la interfaz gráfica:

  • Tk(): Crea la ventana principal.
  • title(): Establece el título de la ventana.
  • resizable(): Hace que la ventana no sea redimensionable.
  • iconbitmap(): Establece el ícono de la ventana.
root = Tk()
root.title("Digital Clock")
root.resizable(0, 0)
root.iconbitmap("clock.ico")

Definimos la función para mostrar la hora:

  • strftime: Formatea la hora actual a una cadena específica.
  • config: Configura el texto del widget Label.
  • after: Programa la actualización de la hora cada segundo.
deftime():
     string = strftime('%H:%M:%S %p')
     lbl.config(text=string)
     lbl.after(1000, time)

Configuramos el widget Label:

  • font: Define la fuente, tamaño y estilo del texto.
  • background: Establece el color de fondo del widget.
  • foreground: Establece el color del texto.
lbl = Label(root, font=('calibri', 40, 'bold'),
             background='#100720',
             foreground='white')

lbl.pack(anchor='center')

Iniciamos la aplicación:

  • time(): Llama a la función para mostrar la hora.
  • mainloop(): Inicia el bucle principal de la interfaz gráfica.
time()
root.mainloop()

Código Completo

from tkinter import *
from tkinter.ttk import *
from time import strftime
root = Tk()
root.title("Digital Clock")
root.resizable(0, 0)
root.iconbitmap("clock.ico")

def time():
     string = strftime('%H:%M:%S %p')
     lbl.config(text=string)
     lbl.after(1000, time)
lbl = Label(root, font=('calibri', 40, 'bold'),
             background='#100720',
             foreground='white')
lbl.pack(anchor='center')

time()
mainloop()

¿Te gustó lo que leíste?

Suscríbete para recibir los nuevos posts en tu email.