使用ttk,您必须创建一堆样式并在它们之间循环。那将是荒谬的,也是不必要的。使用tk,您可以即时更改背景(或任何其他属性)。它更适合您想要的行为。
您不必使用我的deque 方法。您可以继续增加一些整数并重置它。您还可以执行以下操作:self.colors.append(self.colors.pop(0)) ~ 这与 deque 所做的基本相同,作为代理。这里真正的重点是after 用于继续运行一个循环遍历颜色列表的方法,并将当前颜色应用于按钮。
import tkinter as tk
from collections import deque
class GlowButton(tk.Button):
def __init__(self, master, **kwargs):
tk.Button.__init__(self, master, **kwargs)
#store background color
self.bg_idle = self.cget('background')
#list of glow colors to cycle through
self.colors = ['#aa88aa', '#aa99aa', '#aaaaaa', '#aabbaa', '#aaccaa', '#aaddaa', '#aaeeaa', '#aaffaa']
#deque to use as an offset
self.col_index = deque(range(len(self.colors)))
#eventual reference to after
self.glow = None
#add MouseOver, MouseOut events
self.bind('<Enter>', lambda e: self.__glow(True))
self.bind('<Leave>', lambda e: self.__glow(False))
def __glow(self, hover):
if hover:
#get rotation offset
ofs = self.col_index.index(0)
#apply color from rotation offset
self.configure(background=self.colors[ofs])
#if the offset has not reached the end of the color list
if ofs != len(self.colors)-1:
#rotate
self.col_index.rotate(1)
#do all of this again in 50ms
self.glow = self.after(50, self.__glow, hover)
else:
#kill any expected after
self.after_cancel(self.glow)
#rewind
self.col_index.rotate(-self.col_index.index(0))
#reset to idle color
self.configure(background=self.bg_idle)
root = tk.Tk()
GlowButton(root, text='button', font='Helvetica 10 bold', bg='#aa88aa').grid()
if __name__ == '__main__':
root.mainloop()