Tkinter Hovering over Button -gt; Color change(Tkinter 悬停在按钮上-gt;颜色变化)
问题描述
是否有可能在 Button 上悬停后更改其背景颜色?Tkinter 中的代码是什么?
Is there a possibility to change the background-color of a Button after hovering on it? What is the code for this in Tkinter?
推荐答案
遗憾的是,activebackground 和 activeforeground 选项似乎仅在您单击按钮时才起作用,而不是当您将鼠标悬停在按钮上时.改用 <Leave> 和 <Enter> 事件
Sadly the activebackground and activeforeground options only seem to work when you are clicking on the button rather than when you hover over the button. Use the <Leave> and <Enter> events instead
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()
正如评论中指出的,如果我们想要多个按钮,我们可以将按钮绑定到使用点击事件的事件数据来改变按钮背景的函数.
As pointed out in the comments, if we want multiple buttons, we can bind the buttons to functions that use the event data for the click event to change the background of the button.
import tkinter as tk
def on_enter(e):
e.widget['background'] = 'green'
def on_leave(e):
e.widget['background'] = 'SystemButtonFace'
root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()
myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)
myButton2 = tk.Button(root,text="Click Me")
myButton2.grid()
myButton2.bind("<Enter>", on_enter)
myButton2.bind("<Leave>", on_leave)
root.mainloop()
为多个按钮执行此操作的一种更巧妙的方法是创建一个新的 Button 类,该类修改默认按钮的行为,以便 activebackground 在您悬停时实际工作.
A slicker way to do it for multiple buttons would be to create a new Button class that modifies the behaviour of the default button so that the activebackground actually works when you hover.
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()
这篇关于Tkinter 悬停在按钮上->颜色变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Tkinter 悬停在按钮上->颜色变化
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
