遗憾的是,activebackground
and activeforeground
选项仅在单击按钮时才起作用,而不是将鼠标悬停在按钮上时才起作用。使用<Leave>
和<Enter>
事件代替
import tkinter as tk
def on_enter(e):
myButton['background'] = 'green'
def on_leave(e):
myButton['background'] = 'SystemButtonFace'
root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()
myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
对多个按钮执行此操作的一种简便方法是创建一个新的Button类,该类修改默认按钮的行为,以便activebackground
在悬停时可以实际使用。
import tkinter as tk
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
root = tk.Tk()
classButton = HoverButton(root,text="Classy Button", activebackground='green')
classButton.grid()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
干净利落
上下文:基于 Unix 的计算机,可能不适用于 Windows 或 MACOSX
在您的Button
对象属性中,您有标签:activebackground
& activeforeground
,每当与创建的实例进行交互时,这些标签就会被激活。即:您创建的按钮对象。
例如
from tkinter import *
root = Tk()
button = Button(root, text="Click me", bg="#000", fg="#fff", activebackground="#f00", activeforeground="#fff")
button.pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5816 次 |
最近记录: |