透明背景在Tkinter窗口里

for*_*ser 10 python transparency tkinter

有没有办法使用Tkinter在Python 3.x中创建"加载屏幕"?我的意思是像Adobe Photoshop的加载屏幕,具有透明度等.我设法摆脱框架边框已经使用:

root.overrideredirect(1)
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

root.image = PhotoImage(file=pyloc+'\startup.gif')
label = Label(image=root.image)
label.pack()
Run Code Online (Sandbox Code Playgroud)

图像显示正常,但灰色窗口背景而不是透明度.

有没有办法为窗口添加透明度,但仍能正确显示图像?

dln*_*385 26

这是可能的,但它依赖于操作系统.这适用于Windows:

import Tkinter as tk # Python 2
import tkinter as tk # Python 3
root = tk.Tk()
# The image must be stored to Tk or it will be garbage collected.
root.image = tk.PhotoImage(file='startup.gif')
label = tk.Label(root, image=root.image, bg='white')
root.overrideredirect(True)
root.geometry("+250+250")
root.lift()
root.wm_attributes("-topmost", True)
root.wm_attributes("-disabled", True)
root.wm_attributes("-transparentcolor", "white")
label.pack()
label.mainloop()
Run Code Online (Sandbox Code Playgroud)


Jos*_*lin 7

这是macOS的解决方案:

import tkinter as tk

root = tk.Tk()
# Hide the root window drag bar and close button
root.overrideredirect(True)
# Make the root window always on top
root.wm_attributes("-topmost", True)
# Turn off the window shadow
root.wm_attributes("-transparent", True)
# Set the root window background color to a transparent color
root.config(bg='systemTransparent')

root.geometry("+300+300")

# Store the PhotoImage to prevent early garbage collection
root.image = tk.PhotoImage(file="photoshop-icon.gif")
# Display the image on a label
label = tk.Label(root, image=root.image)
# Set the label background color to a transparent color
label.config(bg='systemTransparent')
label.pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

屏幕截图

(在macOS Sierra 10.12.21上测试)

  • 非常感谢你做的这些。你能解释一下为什么你需要`root.wm_attributes("-transparent", True)`和`root.config(bg='systemTransparent')`。它有什么作用?它完美地工作,但解释有点模糊 (2认同)
  • MacOS BigSur 11.7 上的 label.config(bg='systemTransparent') 使窗口完全透明,包括图像。如果我不添加此行,则图像的背景为灰色。 (2认同)

小智 7

只需使用 即可root.config(bg=''),例如:

from tkinter import *
root = Tk()
root.configure(bg='')
Run Code Online (Sandbox Code Playgroud)

  • 至少在 Linux 上,这似乎是有效的 - 直到您移动窗口并意识到它包含其所覆盖内容的快照而不是透明的。 (3认同)

Bry*_*ley 5

在tkinter中,没有跨平台的方法可以使背景透明。