如何使按鈕懸停改變 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