gpt4 book ai didi

python - 有没有办法(或库)在 tkinter 中进行平滑的颜色过渡?

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:24 27 4
gpt4 key购买 nike

首先,介绍一些场景。我有一个 tkinter 窗口,上面有一个按钮。这个按钮是白色的,直到我将鼠标悬停在它上面,在这种情况下它会变成橙色。我的问题是:如何使白色和橙色之间的过渡平滑,就像淡入和淡出一样。到目前为止我的代码:

from tkinter import *
from functools import partial

root = Tk()

def bg_config(widget, bg, fg, event):
widget.configure(background=bg, foreground=fg)
#Fading effect here

btn = Button(root, text="Button", relief=GROOVE, bg="white")

btn.bind("<Enter>", partial(bg_config, btn, "#f47142", "white"))
btn.bind("<Leave>", partial(bg_config, btn, "white", "black"))

bt.pack()
root.mainloop()

我确实有 wxPython 库,如果有帮助的话。是否有任何其他 GUI 库或方法可以使此类任务变得更容易?

最佳答案

这可以通过迭代两种不同颜色(橙色、白色)的rgb值的差异来实现。此外,还有其他 python 库,如 colour这使得工作变得更加容易。在这里,我创建了一个使用 colour 的函数库来淡入和淡出小部件的不同颜色选项。

def fade(widget, smoothness=4, cnf={}, **kw):
"""This function will show faded effect on widget's different color options.

Args:
widget (tk.Widget): Passed by the bind function.
smoothness (int): Set the smoothness of the fading (1-10).
background (str): Fade background color to.
foreground (str): Fade foreground color to."""

kw = tk._cnfmerge((cnf, kw))
if not kw: raise ValueError("No option given, -bg, -fg, etc")
if len(kw)>1: return [fade(widget,smoothness,{k:v}) for k,v in kw.items()][0]
if not getattr(widget, '_after_ids', None): widget._after_ids = {}
widget.after_cancel(widget._after_ids.get(list(kw)[0], ' '))
c1 = tuple(map(lambda a: a/(65535), widget.winfo_rgb(widget[list(kw)[0]])))
c2 = tuple(map(lambda a: a/(65535), widget.winfo_rgb(list(kw.values())[0])))
colors = tuple(colour.rgb2hex(c, force_long=True)
for c in colour.color_scale(c1, c2, max(1, smoothness*100)))

def worker(count=0):
if len(colors)-1 <= count: return
widget.config({list(kw)[0] : colors[count]})
widget._after_ids.update( { list(kw)[0]: widget.after(
max(1, int(smoothness/10)), worker, count+1) } )
worker()
<小时/>

这是正确使用它的示例。

enter image description here

from tkinter import *
from functools import partial
import colour

root = Tk()

def bg_config(widget, bg, fg, event):
fade(widget, smoothness=5, fg=fg, bg=bg)

btn = Button(root, text="Button", relief=GROOVE, bg="white")

btn.bind("<Enter>", partial(bg_config, btn, "#f47142", "white"))
btn.bind("<Leave>", partial(bg_config, btn, "white", "black"))

btn.pack(padx=20, pady=20)
root.mainloop()

关于python - 有没有办法(或库)在 tkinter 中进行平滑的颜色过渡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com