You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter无边框窗口中显示PNG图片的透明效果?

解决Tkinter无边框窗口PNG透明显示问题

你的代码中PNG透明区域显示为白色,是因为窗口未启用透明属性,Canvas默认背景色为白色导致的。只需两处修改就能实现透明效果:

  1. 为主窗口设置透明规则,将窗口默认背景色设为透明:
root.attributes('-transparentcolor', root['bg'])
  1. 创建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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:20:20