Python Tkinter 中颜色的亮度
我知道在tkinter里不能使用透明度或者HSL颜色表示法。不过我想问的是,能不能让任何颜色(除了黑色)不断地变成白色,而不使用其他颜色,只用选定颜色的不同明暗和色调。比如说,我想让我的矩形在1分钟内从棕色逐渐变成白色。我只有一个整数或浮点数的值,可以用这个值来改变颜色。有什么想法吗?
1 个回答
3
是的,这是可以做到的。你想要的其实和在棕色和白色之间创建渐变没有什么区别。不过,你并不是想一次性显示整个渐变,而是想每次只显示一种颜色,持续几毫秒。
下面的代码是根据这个回答改编的:https://stackoverflow.com/a/11893324/7432。
注意:为了演示方便,我把颜色变化的时间设置为6秒,而不是60秒,这样你就不用等那么久就能看到完整效果。
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.rect = tk.Frame(width=200, height=200)
self.rect.pack(fill="both", expand=True, padx=20, pady=20)
# compute a list of colors that form a gradient between
# a starting and ending color, then slowly adjust the background
# of the rectangle according to the computed colors
self.colors = self._compute_colors("brown", "white", 60)
self._adjust_colors()
def _adjust_colors(self):
color = self.colors.pop(0)
self.rect.configure(background=color)
if len(self.colors) > 0:
self.after(100, self._adjust_colors)
def _compute_colors(self, start, end, limit):
(r1,g1,b1) = self.winfo_rgb(start)
(r2,g2,b2) = self.winfo_rgb(end)
r_ratio = float(r2-r1) / limit
g_ratio = float(g2-g1) / limit
b_ratio = float(b2-b1) / limit
colors = []
for i in range(limit):
nr = int(r1 + (r_ratio * i))
ng = int(g1 + (g_ratio * i))
nb = int(b1 + (b_ratio * i))
color = "#%4.4x%4.4x%4.4x" % (nr,ng,nb)
colors.append(color)
return colors
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True);
root.mainloop()