最近更新于 2025-06-09 09:27
blinkbutton.py
import tkinter as tk
class BlinkingButton(tk.Button):
def __init__(self, master=None, blinkColor="red", blinkInterval=500, **kwargs):
"""
闪烁按钮
Args:
master: 父组件
blinkColor: 闪烁颜色
blinkInterval: 闪烁周期(毫秒)
kwargs: 其它Button属性
"""
super().__init__(master, **kwargs)
self.master = master
self._blinkColor = blinkColor
self._blinkInterval = blinkInterval
self._normalBg = self["bg"] if "bg" in kwargs else self.cget("bg")
self._blinking = False
self._blinkState = False
def startBlinking(self):
if not self._blinking:
self._blinking = True
self._blink()
def stopBlinking(self):
self._blinking = False
self.configure(bg=self._normalBg)
def _blink(self):
if not self._blinking:
return
new_color = self._blinkColor if not self._blinkState else self._normalBg
self.configure(bg=new_color)
self._blinkState = not self._blinkState
self.after(self._blinkInterval, self._blink)
class App(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.master = master
self.pack()
def _onChangeButtonText(self):
buttonText = self.blinkingButton['text']
if buttonText == "开始闪烁":
self.blinkingButton.startBlinking()
self.blinkingButton.config(text="停止闪烁")
else:
self.blinkingButton.stopBlinking()
self.blinkingButton.config(text="开始闪烁")
def createWidgets(self):
self.blinkingButton = BlinkingButton(self, 'red', 500, text='开始闪烁', command=self._onChangeButtonText)
self.blinkingButton.pack()
# 示例程序
if __name__ == "__main__":
root = tk.Tk()
root.title("闪烁按钮示例")
root.geometry("300x50")
app = App(root)
app.createWidgets()
root.mainloop()
基于 tkinter Button 实现的可以闪烁的按钮