Home Backend Development Python Tutorial How to create a dynamic Wallpaper with Time and Date using Python

How to create a dynamic Wallpaper with Time and Date using Python

Dec 12, 2024 pm 12:23 PM

Cómo crear un Wallpaper dinámico con la Hora y Fecha usando Python

If you've ever wanted to have a wallpaper that automatically updates with the current time and date, this tutorial is for you. We will use Python and some libraries like PIL (Pillow) to generate an image, add dynamic text with time and date, and then set this image as wallpaper on Windows.

What do we need?

  • Python installed: If you don't have Python installed yet, you can download it from python.org.

  • Install libraries:

    • Pillow: To work with images.
    • ctypes: To interact with the operating system and change the wallpaper in Windows.

You can install Pillow by running the following command in your terminal or cmd: pip install pillow

  • A font file: We need a TrueType font (.ttf) to render the text on the image. In the example code, we use the FiraCode font, but you can use any font you prefer.

1. Imports and initial configuration

At the beginning of the script, we import the necessary libraries and define some initial parameters such as background color, text color, font size and font file path:

from PIL import Image, ImageDraw, ImageFont
import ctypes, os, time, io
from datetime import datetime

background_color = (0, 0, 0)  # Color de fondo (negro)
text_color = (22, 230, 69)  # Color del texto (verde)
font_size = 30
font_path = r"c:/Users/david/Desktop/FiraCodeRegular.ttf"  # Ruta de la fuente
font = ImageFont.truetype(font_path, font_size)

screen_width = 1920
screen_height = 1080
Copy after login
Copy after login
  • Pillow (Image, ImageDraw, ImageFont) is used to create the image and draw the text.
  • ctypes is used to change the wallpaper in Windows.
  • time and datetime allow us to manage times and dates.
  • background_color and text_color are the colors that we will use for the background and text.

2. Formatting the date and time

We define a function to ensure that the date and time numbers are always formatted with two digits:

def two_digits_format(number):
    return f"0{number}" if number < 10 else number
Copy after login
Copy after login

For example, day "5" will be formatted as "05", and the same will happen with the hour, minute and second.

3. Generate the image with the date and time

The add_text_to_image() function creates a new blank image with the size of the screen (in this case, 1920x1080) and draws the text in the center:

def agregar_texto_a_imagen():
    now = datetime.now()

    texto = f"""{{
    "date": {{
        "day": {two_digits_format(now.day)},
        "month": {two_digits_format(now.month)},
        "year": {now.year}
    }},
    "time": {{
        "hour": {two_digits_format(now.hour)},
        "minute": {two_digits_format(now.minute)},
        "second":  {two_digits_format(now.second)},
        "meridiem": "{now.strftime("%p")}"
    }}
}}"""
Copy after login

In this function, we get the current date and time using datetime.now(), and then format the text into JSON format. This is rendered in the image we generated.

Then, we calculate the center of the screen to place the text there:

bbox = draw.textbbox((0, 0), texto, font=font)
ancho_texto = bbox[2] - bbox[0]
altura_texto = bbox[3] - bbox[1]
posicion_x = (ancho_imagen - ancho_texto) // 2
posicion_y = (altura_imagen - altura_texto) // 2
posicion = (posicion_x, posicion_y)
Copy after login

4. Set the image as wallpaper

The set_as_wallpaper() function saves the generated image as a temporary file and then sets it as the wallpaper:

from PIL import Image, ImageDraw, ImageFont
import ctypes, os, time, io
from datetime import datetime

background_color = (0, 0, 0)  # Color de fondo (negro)
text_color = (22, 230, 69)  # Color del texto (verde)
font_size = 30
font_path = r"c:/Users/david/Desktop/FiraCodeRegular.ttf"  # Ruta de la fuente
font = ImageFont.truetype(font_path, font_size)

screen_width = 1920
screen_height = 1080
Copy after login
Copy after login

Here, ctypes.windll.user32.SystemParametersInfoW is a Windows function that allows you to change the wallpaper.

5. Continuous updating of the wallpaper

In the while True: loop, the image is generated and set as wallpaper once per second:

def two_digits_format(number):
    return f"0{number}" if number < 10 else number
Copy after login
Copy after login

This loop ensures that the wallpaper is updated every second with the current time and date.

Full code here: GitHub

Conclusion

This code offers a simple way to generate a dynamic wallpaper that always shows the current time and date. You can customize the appearance of the wallpaper by adjusting the colors, font, and image size. Additionally, the code is designed to be efficient, with the wallpaper updating occurring every second.

If you're looking for a fun way to learn about image manipulation in Python and how to interact with the operating system, this project is a great starting point.

The above is the detailed content of How to create a dynamic Wallpaper with Time and Date using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles