I want to change my background and foreground colour of a button on mouse cursor hover in the Python Tkinter module. I am able to change the background colour of the button once before packing it to the main window.
But after the window.mainloop()
line I cannot execute anymore line until the main window destroyed (or closed).
I am asking that is there any way to change the button colour (background and foreground) on mouse hover even after the window.mainloop()
line?
My code
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()
You can use <Enter>
and <Leave>
events to change the fg
and bg
color of the button:
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()