Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีทำให้ปุ่ม Hover เปลี่ยนสีพื้นหลังใน Tkinter


Widget Button ใน Tkinter มีฟีเจอร์ในตัวมากมายสำหรับกำหนดค่าและทำงานบางอย่างในแอปพลิเคชัน เพื่อรันเหตุการณ์เฉพาะในแอปพลิเคชัน ให้ใช้เมธอด bind("", callback) ผูกฟังก์ชันหรือเหตุการณ์กับปุ่ม เพื่อเพิ่มคุณสมบัติ hover ในปุ่ม ให้ใช้พารามิเตอร์ และ ในฟังก์ชัน bind

ตัวอย่าง

# 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("", change_bgcolor)
    b.bind("", change_fgcolor)

win.mainloop()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มีปุ่ม

วิธีทำให้ปุ่ม Hover เปลี่ยนสีพื้นหลังใน Tkinter

เมื่อวางเมาส์บนปุ่ม จะเปลี่ยนสีพื้นหลังของหน้าต่างหลัก

วิธีทำให้ปุ่ม Hover เปลี่ยนสีพื้นหลังใน Tkinter