【问题标题】:how to make ttk widget glow slowly when hovered悬停时如何使ttk小部件缓慢发光
【发布时间】:2021-03-14 01:44:11
【问题描述】:

我试图让我的ttk 小部件在悬停时像messagebox OK 按钮一样缓慢发光。 在您的代码编辑器中输入此代码,然后将鼠标悬停在“确定”按钮上,看看我所说的小部件缓慢发光是什么意思。

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 小部件在悬停时缓慢发光吗?

【问题讨论】:

    标签: python tkinter button hover ttk


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2010-12-04
      相关资源
      最近更新 更多