如何使按钮悬停改变 Tkinter 中的背景颜色?
Tkinter 中的按钮小工具具有许多内置特性,可用于配置和执行应用程序中的某些任务。为了在应用程序中运行特定事件,我们可以使用 bind("<Buttons>", callback) 方法将函数或事件与按钮绑定。要添加按钮中的 悬停 特性,可以在 bind 函数中使用 <Enter> 和 <Leave> 参数。
示例
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
def change_bgcolor(e):
win.config(background="green3")
def change_fgcolor(e):
win.config(background="white")
# Add Buttons to trigger the event
b1=Button(win, text="Hover on Me", font=('Georgia 16'))
b1.pack(pady=60,anchor=CENTER)
# Bind the events
for b in [b1]:
b.bind("<Enter>",change_bgcolor)
b.bind("<Leave>", change_fgcolor)
win.mainloop()输出
如果我们运行以上代码,它将显示一个包含按钮的窗口。
当我们在按钮上悬停鼠标时,它将改变主窗口的背景色。

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP