You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

python
复制代码
import tkinter as tk
from PIL import Image, ImageTk
class TkinterBackground:
def __init__(self, root, image_path):
self.root = root
self.set_image_as_background(image_path)
def set_image_as_background(self, image_path):
# 加载图片
img = Image.open(image_path)
# 确保图片与窗口大小匹配,或者你可以调整图片大小
img = img.resize((self.root.winfo_reqwidth(), self.root.winfo_reqheight()), Image.Resampling.LANCZOS)
# 使用PIL的ImageTk将PIL Image转换为Tkinter的PhotoImage
photo = ImageTk.PhotoImage(img)
# 创建一个Canvas来放置图片
self.canvas = tk.Canvas(self.root, width=self.root.winfo_reqwidth(), height=self.root.winfo_reqheight())
self.canvas.pack(fill="both", expand=True)
# 在Canvas上放置图片
self.canvas.create_image(0, 0, image=photo, anchor="nw")
# 保持对PhotoImage的引用否则它会被Python的垃圾回收机制回收
self.canvas.image = photo
# 使用示例
root = tk.Tk()
root.title("Image Background")
# 设置窗口大小(可选,你可以根据需要设置)
root.geometry("400x300")
# 创建一个TkinterBackground的实例并设置图片背景
background = TkinterBackground(root, "path_to_your_image.jpg") # 替换为你的图片路径
# 运行Tkinter事件循环
root.mainloop()