在我的新应用程序中,我希望当鼠标位于entry()小部件上方以改变颜色时(我知道该怎么做)但我希望颜色逐渐改变,而不是立即改变。
这是我的代码:
# User_Line Focus In/Out
def User_Line_Focus_In(self, event):
self.User_Line.configure(bg = "#DCDCDC")
def User_Line_Focus_Out(self, event):
self.User_Line.configure(bg = "#FFFFFF")
答案 0 :(得分:2)
您需要创建一个增加颜色的方法,并且需要使用tkinter的after
来注册在给定时间后调用的警报回调。然后,您需要递归引用它以获得所需的淡化效果。
def incrementHex(hex_str, increment): #with hex_str in format "#FFFFFF" or any colour
red = int(hex_str[1:3],16) #specifies base for integer conversion
green = int(hex_str[3:5],16)
blue = int(hex_str[5:],16)
red += increment #increment can be negative
green += increment
blue += increment
new_hex_str = "#" + str(hex(red)) + str(hex(blue)) + str(hex(green))
return new_hex_str
def Fade(self, start_hex, increment):
new_hex = self.incrementHex(start_hex, increment)
self.User_Line.configure(bg = new_hex)
#where self.master is the parent widget as defined in the __init__ method...
self.master.after(50,lambda: self.Fade(new_hex, increment)) #or any time interval in milliseconds
#you'll probably need some code to stop it fading here, but I'll let you tackle that one :)
def User_Line_Focus_In(self, event):
self.Fade("#FFFFFF",-1) #could be any colour and increment
我无法测试它,但我认为原则上应该可行。对此的扩展是对红色,绿色和蓝色有不同的增量。
答案 1 :(得分:0)
我认为你将不得不在这个问题上拉扯你的袜子并做一些编码(tkinter没有内置它)
所以你要找的是:
最简单的解决方案是运行算法(此处为color_difference)
def fade_colors(event, new_color):
old_color = event.widget.cget('bg')
for color in color_difference(old_color, new_color):
event.widget.configure(color)
time.sleep(0.1)
widget.bind('<Enter>', lambda event: fade_colors(event, color))
如果您发现gui在淡入淡出过程中没有响应,可以考虑使用after方法,您可以在python和tkinter中阅读this excellent blog关于非阻塞gui技术的帖子。如果您在用户离开窗口小部件后立即取消回调(从而释放tkinter来处理其他操作),这可能不是问题。