How to add a background image to a Python window

To add a background image in a Python window, you can use the tkinter module. Here is a simple example code showing how to add a background image in a Python window.

import tkinter as tk
from PIL import Image, ImageTk

# 创建窗口
window = tk.Tk()

# 加载背景图片
image = Image.open("background.jpg")
background_image = ImageTk.PhotoImage(image)

# 创建背景图片标签
background_label = tk.Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

# 添加其他组件
label = tk.Label(window, text="Hello, World!", font=("Arial", 24))
label.pack()

# 运行窗口
window.mainloop()

In the code above, we first imported the tkinter module and the PIL module (used for image processing), and then created a window object. Next, we loaded a background image using the Image.open() method and converted it to an ImageTk.PhotoImage object. Then, we created a label object background_label and placed it at the top left corner of the window using the place() method. Finally, we added a simple label component and called window.mainloop() to run the window.

Please note that you need to ensure that the image file (in the example above, background.jpg) is in the same directory as the Python file, or you can provide the full path to the image file.

广告
Closing in 10 seconds
bannerAds