Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-11-20· OpenAIAi2 WildChat-4.8M (AI2)

Python code clock

  1. User

    Python code clock

  2. Assistant

    Sure! Below is an example of a simple digital clock program written in Python using the tkinter library:

    import time
    import tkinter as tk
    
    # Function to update the time on the label
    def update_clock():
        current_time = time.strftime("%H:%M:%S")
        clock_label.config(text=current_time)
        clock_label.after(1000, update_clock)  # Call the function again after 1 second
    
    # Create a window using tkinter
    root = tk.Tk()
    root.title("Digital Clock")
    
    # Create a label to display the time
    clock_label = tk.Label(root, font=("Helvetica", 48), fg="white", bg="black")
    clock_label.pack()
    
    # Start the clock
    update_clock()
    
    # Run the tkinter main event loop
    root.mainloop()
    

    How it works:

    1. The time.strftime("%H:%M:%S") function gets the current time in hours, minutes, and seconds.
    2. The update_clock function updates the time on the label every second using the after method.
    3. The tk.Label widget is used to display the time in a visually appealing format.
    4. The tk.mainloop() runs the tkinter graphical user interface.

    To run this code:

    • Save it to a .py file, e.g., digital_clock.py.
    • Run it using Python.

    This will create a window displaying the current time that updates every second! Feel free to modify the font, colors, and size to customize your clock.