Search code examples
pythonuser-interfacetkintercustomtkinter

How to make it so the background changes of a rounded button using custom tkinter, when it is hovered over by the mouse?


Here is my current code:

from tkinter import *
from tkinter.ttk import *
from customtkinter import *
main = CTk()


start_button = CTkButton(main, 
                             text = "Start",
                             command=lambda: inputscreen(),
                             corner_radius=50,
                             height=50,
                             width=70,
                             fg_color="#FFFFFF",
                             text_color = "#00EC00",
                             hover_color="#00EC00",
                             hover=True)
    
    start_button.bind("<Enter>", lambda event: 
                  start_button.configure(text_color="white"),fg_color = "#00EC00")

    start_button.bind("<Leave>", lambda event: 
                      start_button.configure(text_color="#00EC00",fg_color = "white"))

Hover_colour, doesn't seem to change the colour. at the start_button.configure, fg_color, returns an error, and bg_color, changes the corner color as well, so the button no long looks rounded.

I tried the above code, and it just returns and error


Solution

  • You can create a CustomTKinter button with the desired hover and foreground colors by setting the hover_color and fg_color attributes, without using the enter and leave events.

    Thus it would look like this:

    from tkinter.ttk import *
    from customtkinter import *
    main = CTk()
    
    
    start_button = CTkButton(main, 
                                 text = "Start",
                                 command=lambda: inputscreen(),
                                 corner_radius=50,
                                 height=50,
                                 width=70,
                                 fg_color="#FFFFFF",
                                 text_color = "#00EC00",
                                 hover_color="#00EC00",
                                 hover=True);
    

    The enter event has a syntax error: an extra ) that causes the failure.

    start_button.bind("<Enter>", lambda event: 
                      start_button.configure(text_color="white"),fg_color = "#00EC00")