如何在Tkinter无边框窗口中显示PNG图片的透明效果?
解决Tkinter无边框窗口PNG透明显示问题
你的代码中PNG透明区域显示为白色,是因为窗口未启用透明属性,Canvas默认背景色为白色导致的。只需两处修改就能实现透明效果:
- 为主窗口设置透明规则,将窗口默认背景色设为透明:
root.attributes('-transparentcolor', root['bg'])
- 创建Canvas时,将其背景色与主窗口保持一致,让图片透明区域能穿透到窗口层面:
canvas = tk.Canvas(root, width=image.width, height=image.height, bd=0, highlightthickness=0, bg=root['bg'])
修改后的完整代码:
import tkinter as tk from PIL import Image, ImageTk import pygame.mixer import signal import time def on_exit(signum, frame): print("closed by admin") time.sleep(5) signal.signal(signal.SIGTERM, on_exit) pygame.mixer.init() root = tk.Tk() root.attributes('-topmost', True) root.overrideredirect(True) # 添加窗口透明设置 root.attributes('-transparentcolor', root['bg']) image = Image.open('OIP.png') photo = ImageTk.PhotoImage(image) screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() x = (screen_width // 2) - (image.width // 2) y = (screen_height // 2) - (image.height // 2) root.geometry(f'{image.width}x{image.height}+{x}+{y}') # Canvas背景设为窗口背景色 canvas = tk.Canvas(root, width=image.width, height=image.height, bd=0, highlightthickness=0, bg=root['bg']) canvas.create_image(image.width // 2, image.height // 2, image=photo) canvas.pack() def close_window(event): root.destroy() pygame.mixer.music.stop() root.bind('<Escape>', close_window) root.mainloop()
说明:
- 该方案在Windows系统下表现稳定,通过标记窗口默认背景色为透明,让Canvas背景与窗口同步,从而实现PNG透明区域的显示效果。
- 若在Linux或macOS环境使用,可能需要调整为
root.attributes('-alpha', 1)配合其他设置,但上述方法是Windows环境下最直接的解决方式。
内容的提问来源于stack exchange,提问作者BatteTarte
相关产品推荐
相关产品推荐

