首先,一点情景。我有一个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库或方法可以使这些任务更容易?
答案 0 :(得分:3)
这可以通过迭代两种颜色(橙色,白色)的 rgb 值的差异来实现。另外,还有其他colour之类的python库,使工作变得更加容易。在这里,我做了一个使用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()
以下是正确使用它的示例。
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()
答案 1 :(得分:1)
tkinter中没有任何内容可以直接支持此功能。您需要通过创建一个每隔几毫秒运行一次并慢慢改变颜色的函数来完成它。