首页 > 解决方案 > 如何在 tinter 中创建半透明窗口?

问题描述

我正在尝试在 Tkinter 中创建一个半透明窗口,就像 Windows 11 中的那样在此处输入图像描述

这个怎么做?如果我们不能做到这一点,我们是否可以捕获屏幕的一部分并使用 cv2 对其进行模糊处理并将其用作不断更新的背景?

标签: pythonuser-interfacetkinterwindow

解决方案


不,这不能直接用tkinter. 但:

如果你使用PIL,你可以获取窗口的位置,然后截图,然后模糊它,然后将它作为你的应用程序背景。但是,如果用户尝试移动/调整应用程序的大小,这将不起作用。但这里有一个粗略的代码:

from tkinter import *
from PIL import ImageTk, ImageGrab, ImageFilter # pip install Pillow

root = Tk()
root.overrideredirect(1) # Hide the titlebar etc..

bg = Canvas(root)
bg.pack(fill='both',expand=1)
root.update()

# Get required size and then add pixels to remove title bar and window shadow
left   = root.winfo_rootx()
top    = root.winfo_rooty()
right  = left + root.winfo_width()
bottom = top  + root.winfo_height()

root.withdraw() # Hide the window
img = ImageGrab.grab((left,top,right,bottom)) # Get the bg image
root.deiconify() # Show the window

img = img.filter(ImageFilter.GaussianBlur(radius=5)) # Blur it 
img = ImageTk.PhotoImage(img)
bg.create_image(0,0, image=img, anchor='nw') # Show in canvas

label = Label(root,text='This is a translucent looking app')
bg.create_window(bg.winfo_width()/2,bg.winfo_height()/2,window=label) # Position in the center

root.mainloop()

输出tkinter


tkinter如果您想追求现代外观,使用PyQt和检查qtacrylic不是最佳选择

输出PyQt


推荐阅读