Make a simple time and date display tool with Python

Python is a powerful programming software that can easily meet our various development needs. Today we use the tkinter that comes with Python to develop a clock display. As shown below:

time display

1. Programming requirements

Use tkinter to write a beautiful and multicolored time display. It is required to display hours, minutes, and seconds, which can be changed in real time, and the date should be displayed at the same time.

2. Algorithm analysis

If you don’t need additional packages, use the tkinter that comes with Python, so that the exe file formed after packaging is too small and light, and can be used immediately after opening. First of all, we use the function method to solve this problem, and then we use the class method to further optimize.

1. Realized by function method

In the writing process, we first import the tkinter module and other modules required.

Then, we define two functions update_time() and update_date() for updating time and date labels. The update_time() function uses the time.strftime() function to obtain the current time, and uses the config() method to update it to the time_label.

Next, we use the after() method to call the update_time() function again after 1000 milliseconds (1 second) to achieve instant changes in time. Similarly, the update_date() ref="http://function uses datetime.date.today">The function uses datetime.date.today().strftime() to get the current date and update it on date_label.

Next, we create a tkinter root window and set the window's title, size, and background color. Then, we define the fonts used for time and date, which are large time font and small date font respectively.

Subsequently, we created two labels time_label and date_label for displaying time and date. We center them in the window using the pack() method and set their font and background color using the font parameter.

Finally, we call the update_time() and update_date() functions to start updating the time and date displays, respectively. Then, keep the window open by entering the main event loop by calling root.mainloop() .

Run the code, and you'll see a small, elegant window with a multicolored time display and date display. The time will be displayed in hours, minutes and seconds and will be updated in real time. Dates are displayed in year-month-day format, and the current date is displayed when the window is opened. Note that here we are not using any additional packages, only the time and datetime modules from tkinter and the standard library.

import tkinter as tk
from tkinter import font
import time
import datetime

def update_time():
    current_time = time.strftime('%H:%M:%S')
    time_label.config(text=current_time)
    time_label.after(1000, update_time)

def update_date():
    current_date = datetime.date.today().strftime('%Y-%m-%d')
    date_label.config(text=current_date)

root = tk.Tk()
root.title("时间显示器")
root.geometry("300x200")
root.configure(bg='white')

time_font = font.Font(family="Helvetica", size=48, weight="bold")
date_font = font.Font(family="Helvetica", size=16)

time_label = tk.Label(root, text="", font=time_font, bg='white')
time_label.pack(pady=30)

date_label = tk.Label(root, text="", font=date_font, bg='white')
date_label.pack()

update_time()
update_date()

root.mainloop()

2. Use the class writing method to achieve

When converting the code to a class, we can encapsulate the main functions and interface elements in a custom ClockApp class . The following is a sample code for a time and date display written using classes:

import tkinter as tk
from tkinter import font
import time,datetime

class ClockApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("时间显示器")
        self.geometry("300x200")
        self.configure(bg='white')

        self.time_font = font.Font(family="Helvetica", size=48, weight="bold")
        self.date_font = font.Font(family="Helvetica", size=16)

        self.time_label = tk.Label(self, text="", font=self.time_font, bg='white')
        self.time_label.pack(pady=30)

        self.date_label = tk.Label(self, text="", font=self.date_font, bg='white')
        self.date_label.pack()

        self.update_time()
        self.update_date()

    def update_time(self):
        current_time = time.strftime('%H:%M:%S')
        self.time_label.config(text=current_time)
        self.time_label.after(1000, self.update_time)

    def update_date(self):
        current_date = datetime.date.today().strftime('%Y-%m-%d')
        self.date_label.config(text=current_date)

if __name__ == "__main__":
    app = ClockApp()
    app.mainloop()

In this example, we define a ClockApp class inherited from http://tk.Tk . In the __init__ method, we initialize the title, size and background color of the window, and create time and date labels, setting their font and background color.

The update_time and update_date methods are the same functions as in the previous example, and are used to update the display of time and date. The difference is that we use the self.time_label.after and self.date_label.after methods to call these two methods periodically.

At the end of the code, we create a ClockApp object and run the application's main event loop.

By writing this class, we organize related functions together to make the code more structured and extensible.

3. Use dial display

The above clock is only a digital display, and it doesn’t feel high-end enough. You can change it to a dial with a sentence of cherishing time written on it, and then write the time and date at the bottom, the effect may be better. As shown below:

 In order to achieve the above functions, we need to do the following steps:

Create a ClockApp class inherited from http://tkinter.Tk and initialize the title, size and background color of the window.

Create a Canvas component in the window to draw the dial and place it in the window.

Create a Label component to display the time, place it in the window, and set its font and background color.

Create a Label component to display the date, place it in the window, and set its font and background color.

Call the draw_clock method to draw the dial, including the dial circle and tick marks.

Call the update_clock method to start updating the clock.

In the update_clock method, get the current time and date.

Use the strftime method to format the time as a string and update the text content of the time label.

Use the strftime method to format the date as a string and update the text content of the date label.

Calculate the positions and angles of the hour, minute and second hands and draw them on the dial using the create_line method.

If there is a second hand image object drawn last time, use the canvas.delete method to delete it. Draw a new second hand image and save it to the self.second_hand member variable.

In order to eliminate the movement track of the hour and minute hands, when we draw the hour and minute hands, we need to use the canvas.create_line method to create a new image object and save it to the corresponding member variable.

Use the after method to set a timer, and call the update_clock method every second to update the display of the clock.

Through these steps, we have created a clock application that updates in real time. It displays the current time and date, and draws the hour, minute, and second hands on the dial so that they update according to the actual time. At the same time, the problem that the track of the second hand, hour hand, and minute hand does not disappear has been fixed to ensure that the second hand displays and disappears normally when updating. The following is the optimized clock code display:

import tkinter as tk
from math import cos, sin, pi
from datetime import datetime

class ClockApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("表盘时钟")
        self.geometry("400x450")
        self.configure(bg='light green')

        self.motto_label = tk.Label(self, text="时不待我,只争朝夕!",font=('楷体', 16,'bold'), bg='light green')
        self.motto_label.pack()
        
        self.canvas = tk.Canvas(self, width=400, height=360, bg='light green', highlightthickness=0)
        self.canvas.pack()

        self.time_label = tk.Label(self, font=('Helvetica', 16), bg='light green')
        self.time_label.pack(pady=10)

        self.date_label = tk.Label(self, font=('Helvetica', 12), bg='light green')
        self.date_label.pack()

        self.hour_hand = None  # 保存时针图像对象
        self.minute_hand = None  # 保存分针图像对象
        self.second_hand = None  # 保存秒针图像对象

        self.draw_clock()
        self.update_clock()

    def draw_clock(self):
        center_x = 200
        center_y = 200
        radius = 150

        # 绘制表盘
        self.canvas.create_oval(center_x - radius, center_y - radius, center_x + radius, center_y + radius,
                                width=2, outline='blue')

        # 绘制刻度线和小时标识
        for i in range(12):
            angle = (i / 12) * 2 * pi -1/3 * pi
            x1 = center_x + cos(angle) * (radius - 10)
            y1 = center_y + sin(angle) * (radius - 10)
            x2 = center_x + cos(angle) * radius
            y2 = center_y + sin(angle) * radius
            self.canvas.create_line(x1, y1, x2, y2, width=3)
            hour_x = center_x + cos(angle) * (radius - 25)
            hour_y = center_y + sin(angle) * (radius - 25)
            self.canvas.create_text(hour_x, hour_y, text=str(i+1), font=('Helvetica', 12), fill='black')

    def update_clock(self):
        current_time = datetime.now().time()
        current_date = datetime.now().date()

        # 更新时间标签
        time_str = current_time.strftime('%H:%M:%S')
        self.time_label.config(text=time_str)

        # 更新日期标签
        date_str = current_date.strftime('%Y-%m-%d')
        self.date_label.config(text=date_str)

        # 删除上一次的时针和分针图像
        if self.hour_hand:
            self.canvas.delete(self.hour_hand)
        if self.minute_hand:
            self.canvas.delete(self.minute_hand)

        # 更新时针
        hour = current_time.hour
        minute = current_time.minute
        second = current_time.second

        hour_angle = ((hour % 12) + minute / 60 + second / 3600) * (2 * pi / 12) - pi / 2
        hour_length = hour_x = 200 + cos(hour_angle) * 60
        hour_y = 200 + sin(hour_angle) * 60
        self.hour_hand = self.canvas.create_line(200, 200, hour_x, hour_y, width=4, fill='brown')
        
            # 更新分针
        minute_angle = ((minute + second / 60) / 60) * (2 * pi) - pi / 2
        minute_length = 90
        minute_x = 200 + cos(minute_angle) * minute_length
        minute_y = 200 + sin(minute_angle) * minute_length
        self.minute_hand = self.canvas.create_line(200, 200, minute_x, minute_y, width=3, fill='green')

        # 更新秒针
        second_angle = (second / 60.0) * (2 * pi) - pi / 2
        second_length = 120
        second_x = 200 + cos(second_angle) * second_length
        second_y = 200 + sin(second_angle) * second_length
        if self.second_hand:
            self.canvas.delete(self.second_hand)
        self.second_hand = self.canvas.create_line(200, 200, second_x, second_y, width=2, fill='red')

        self.after(1000, self.update_clock)
if __name__ == "__main__":
    app = ClockApp()
    app.mainloop()

3. Post-school reflection

  1. Both the function method and the class writing method can complete the task, but compared with the class writing method, it is more scientific and logical, and how to add functions later is also easy to implement. It is recommended to write in class.
  2. The name of the function should be consistent with its function. The function of the function can be seen from the name at once. For example, the update_time() function is to update the time display.
  3. If you define a label, it can be defined as purpose + attribute. For example, the label of time can be defined as time_label, which is easier to identify.
  4. If you encounter complex programming, you can draw a mind map first, clarify the purpose, implementation steps, etc., and then implement programming step by step.

Guess you like

Origin blog.csdn.net/henanlion/article/details/131503220