滑鼠懸停時更改 Tkinter 中按鈕的顏色
假設我們要建立一個應用程式,其中希望在滑鼠懸停時更改按鈕小部件的顏色。可以透過定義事件回撥來實現懸停屬性。
要在滑鼠懸停時更改按鈕的顏色,我們需要繫結**<Enter>**和**<Leave>**事件。對於每個事件,我們將配置按鈕屬性,例如背景色、前景色等。
示例
#Import required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Define functions
def on_enter(e):
button.config(background='OrangeRed3', foreground= "white")
def on_leave(e):
button.config(background= 'SystemButtonFace', foreground= 'black')
#Create a Button
button= Button(win, text= "Click Me", font= ('Helvetica 13 bold'))
button.pack(pady= 20)
#Bind the Enter and Leave Events to the Button
button.bind('<Enter>', on_enter)
button.bind('<Leave>', on_leave)
win.mainloop()輸出
執行以上程式碼會顯示一個包含按鈕的視窗。
現在,將滑鼠懸停在顯示視窗中的按鈕上。它將更改其基本顏色,例如背景色和前景色。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP