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

如何在Tkinter中实现类似Windows 11效果的半透明窗口?

Tkinter实现Windows 11半透明毛玻璃效果方案

原生API实现(Windows 11专属,性能最优)

Tkinter本身没有内置毛玻璃效果,但在Windows 11系统下可以直接调用系统DWM(桌面窗口管理)API实现原生云母/半透明效果,无需额外截图处理,性能和显示效果都是最好的。

  • 先安装依赖库:pip install pywin32
  • 核心实现代码示例:
import tkinter as tk
import win32con
import win32gui
from ctypes import windll, c_int, byref

# 初始化窗口
root = tk.Tk()
root.title("Win11半透明窗口")
root.geometry("800x600")

# 获取窗口句柄
hwnd = windll.user32.GetParent(root.winfo_id())

# 开启云母效果
DWMWA_MICA_EFFECT = 1029
value = c_int(2) # 2为启用云母效果,1为启用亚克力效果
windll.dwmapi.DwmSetWindowAttribute(hwnd, DWMWA_MICA_EFFECT, byref(value), c_int(4))

# 设置窗口半透明属性
ex_style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, ex_style | win32con.WS_EX_LAYERED)
win32gui.SetLayeredWindowAttributes(hwnd, 0, 220, win32con.LWA_ALPHA) # 220为透明度,0-255可调

root.mainloop()

注意:该方案仅支持Windows 11 22H2及以上版本,低版本Windows系统无法调用对应API

OpenCV截图模拟实现(跨平台兼容)

你提到的用cv2截取屏幕区域模糊作为背景的方案是完全可行的,适合需要跨Windows 10、Linux、macOS等系统的场景,只是性能比原生API差一些。
核心实现逻辑:

  • 将Tkinter窗口设置为分层透明,指定一个特殊的背景色作为透明关键色
  • 每次刷新时先获取窗口当前在屏幕上的坐标和尺寸,截取对应区域的屏幕内容
  • 用cv2.GaussianBlur对截图做高斯模糊处理,再转换为Tkinter支持的图片格式设置为窗口背景
  • 绑定窗口拖动、resize事件,触发时立刻刷新背景,避免显示错位
  • 建议刷新率设置在15-30fps即可,过高会导致CPU占用过高
    简化核心代码示例:
import tkinter as tk
import cv2
import numpy as np
from PIL import Image, ImageTk
import mss # 比pyautogui截图速度快很多

root = tk.Tk()
root.geometry("800x600")
root.title("模拟毛玻璃窗口")
bg_label = tk.Label(root)
bg_label.pack(fill=tk.BOTH, expand=True)

def update_bg():
    # 获取窗口坐标
    x = root.winfo_x()
    y = root.winfo_y()
    w = root.winfo_width()
    h = root.winfo_height()
    # 截取对应屏幕区域
    with mss.mss() as sct:
        monitor = {"top": y, "left": x, "width": w, "height": h}
        img = np.array(sct.grab(monitor))
    # 高斯模糊处理
    img = cv2.GaussianBlur(img, (15, 15), 0)
    # 转换为Tkinter支持的格式
    img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGBA)
    im = Image.fromarray(img)
    tk_img = ImageTk.PhotoImage(image=im)
    bg_label.config(image=tk_img)
    bg_label.image = tk_img
    # 30ms刷新一次,约33fps
    root.after(30, update_bg)

update_bg()
root.mainloop()

内容的提问来源于stack exchange,提问作者peter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 08:24:04