如何使ttk小部件在悬停时缓慢发光



我正试图让我的ttk小部件在像messageboxOK按钮一样悬停时缓慢发光。在代码编辑器中键入此内容,然后将鼠标悬停在"确定"按钮上,查看我所说的小部件缓慢发光的意思。

from tkinter import *
from tkinter import messagebox
messagebox.showinfo("","Hover over OK button!")

但是,当鼠标悬停时,ttk小部件会立即亮起。

from tkinter import *
from tkinter import ttk
root = Tk()
ttk.Button(root, text ="Hover over me!").pack()
root.mainloop()

我可以知道如何使我的ttk小部件在悬停时缓慢发光吗?

使用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()

最新更新