Tkinter有什么方法可以淡出小部件吗?



有没有办法将图像设置为部分透明,也许使用 PIL 或其他东西?我知道tkinterTk()Toplevel()有这样的功能,但我想知道是否有办法将其应用于小部件或 PIL 图像,然后我可以将其放入小部件中,两者都可以。

我想做一个当你输了时会褪黑的游戏,但我不希望整个窗口都消失。

您有两种选择:淡出整个窗口或使用淡出图像PIL,单个小部件不能淡出:

淡出窗外

TkTopLevel窗口可以完全淡出

import time
import threading
import tkinter
root = tkinter.Tk()
def fade():
global root
# Walk backwards through opacities (1 is opaque, 0 is transparent)
i = 1.0
while i >= 0:
root.attributes("-alpha", i)
i -= 0.1
# Sleep some time to make the transition not immediate
time.sleep(0.05)

# Put image fading in a thread so it doesn't block our GUI
fade_thread = threading.Thread(target=fade)
tkinter.Button(root, text="Fade out", command=fade_thread.start).pack()
root.mainloop()

淡出图像

涉及更多,计算密集度更高(较大的图像加剧了这个问题(。可能值得预先计算这些或使用更少的步骤(-10 与 -5 等(以节省一些计算能力。

import time
import threading
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
# Tested with .jpg and .png
IMAGE_PATH = "/path/to/image.jpg"
# Create a pillow image and a tkinter image. convert to RGBA to add alpha channel to image
image = Image.open(IMAGE_PATH).convert("RGBA")
image_tk = ImageTk.PhotoImage(image)
# We'll fade to whatever the background is here (black, white, orange, etc)
label = tkinter.Label(root, image=image_tk, bg="black")
label.pack()
def fade_image():
global image, image_tk, label
# Walk backwards through opacities (255 is opaque, 0 is transparent)
for i in range(255, 0, -5):
image.putalpha(i) # Set new alpha
image_tk = ImageTk.PhotoImage(image) # Cretae new image_tk
label.configure(image=image_tk)
# Sleep some time to make the transition not immediate
time.sleep(0.001)

# Put image fading in a thread so it doesn't block our GUI
fade_thread = threading.Thread(target=fade_image)
tkinter.Button(root, text="Fade To Black", command=fade_thread.start).pack()
root.mainloop()

请注意,在GUI 程序中使用线程和time.sleep(),这是不好的做法。最好使用widget.after(delay_in_ms, callback)。有关如何执行此操作的更多信息,请查看tkinter:如何使用后方法

相关内容

  • 没有找到相关文章

最新更新