python tkinter button颜色变不了_python-Tkinter悬停在按钮上->颜色变化

遗憾的是,activebackground和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("", on_enter)

myButton.bind("", on_leave)

root.mainloop()

对多个按钮执行此操作的一种更轻松的方法是创建一个新的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("", self.on_enter)

self.bind("", 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值