如何在 Tkinter 中更改悬停按钮的背景颜色?

How do I change background colour of a button on hover in Tkinter?

我想在 Python Tkinter 模块中更改鼠标光标悬停时按钮的背景色和前景色。在将按钮打包到主 window 之前,我可以更改一次按钮的背景颜色。 但是在 window.mainloop() 行之后我无法再执行行,直到主 window 被销毁(或关闭)。

我想问一下,即使在 window.mainloop() 行之后,是否有任何方法可以更改鼠标悬停时的按钮颜色(背景和前景)?

我的代码

import tkinter

window = tkinter.Tk()
button = tkinter.Button(window, text="Test", fg='#03045e', command=terminate_instant,
                        relief=tkinter.RIDGE, bg='#caf0f8', activebackground='#ef233c',
                        activeforeground='white')
button.pack(side=tkinter.BOTTOM)
window.mainloop()

您可以使用 <Enter><Leave> 事件来更改按钮的 fgbg 颜色:

import tkinter

window = tkinter.Tk()
button = tkinter.Button(window, text="Test", fg='#03045e', command=terminate_instant,
                        relief=tkinter.RIDGE, bg='#caf0f8', activebackground='#ef233c',
                        activeforeground='white')
button.pack(side=tkinter.BOTTOM)
button.bind("<Enter>", lambda e: button.config(fg='#caf0f8', bg='#03045e'))
button.bind("<Leave>", lambda e: button.config(fg='#03045e', bg='#caf0f8'))
window.mainloop()