Home > Enterprise >  How to change color when hovering over a button in Tkinter?
How to change color when hovering over a button in Tkinter?

Time:09-30

I have made a calculator using tkinter. In that, I wanted to change the color of the buttons when I hover over it. I did change the color of some buttons, but I couldn't change the color of the digits buttons when I hover it.

self.digits = {
         7:(1,1), 8:(1,2), 9:(1,3),
         4:(2,1), 5:(2,2), 6:(2,3),
         1:(3,1), 2:(3,2), 3:(3,3),
         0:(4,2), ".":(4,1), 
     } 

that was the code i used to input the digits.

def create_digit_buttons(self):
      for digit,grid_value in self.digits.items():
          Button =  tk.Button(self.buttons_frame, text=str(digit), bg="#fff", fg="#25265E", font=("Arial", 24, "bold"), borderwidth=0,
                              command=lambda x=digit: self.add_to_expressions(x))
          Button.grid(row=grid_value[0], column=grid_value[1], sticky=tk.NSEW) 

And above code is the one i used for the digit buttons.

    def changedgt_on_hovering(event):
      global create_digit_buttons
      Button['bg']='#F0F0F0'
    
    def returndgt_to_normalstate(event):
      global create_digit_buttons
      Button['bg']='#fff'
    
    Button.bind("<Enter>", changedgt_on_hovering)
    Button.bind("<Leave>",returndgt_to_normalstate)

That was the code i used to change the color of the digits buttons when hovering over them. there's no any error msgs; only decimal point button changes the color when hovering through it, since i added the decimal point(".") to the self.digits part.

below is the full code upto the necessary part...pls help me(I'm a newbie)

from tkinter import *
import tkinter as tk

LABEL_COLOR = "#25265E"
DEFAULT_FONT_STYLE = ("Arial", 20,"bold")
OFF_WHITE = "#F8FAFF"


class Calculator:
    def __init__(self):
        self.window = tk.Tk()
        self.window.geometry("375x660")
        self.window.resizable(height=True, width= True)
        self.window.title("Calculator")
        

        self.total_expression = ""
        self.current_expression = ""

        self.display_frame = self.create_display_frame()
         
        self.total_label, self.label =self.create_display_labels()

        self.digits = {
            7:(1,1), 8:(1,2), 9:(1,3),
            4:(2,1), 5:(2,2), 6:(2,3),
            1:(3,1), 2:(3,2), 3:(3,3),
            0:(4,2), ".":(4,1), 
        }

        self.operations = {"/": "\u00F7", "*": "\u00D7","-": "-", " ": " "}
        self.buttons_frame = self.create_buttons_frame()

        

        self.buttons_frame.rowconfigure(0, weight=1)
        for x in range(1,5):
            self.buttons_frame.rowconfigure(x, weight=1)
            self.buttons_frame.columnconfigure(x, weight=1)
        
       
        self.create_digit_buttons()
        self.create_operator_buttons()
        self.create_special_buttons()
        self.bind_keys()

        


    def bind_keys(self):
        self.window.bind("<Return>", lambda event: self.evaluate())
        self.window.bind("<BackSpace>", lambda event: self.delete())

        for key in self.digits:
            self.window.bind(str(key), lambda event, digits = key: self.add_to_expressions(digits))

        for key in self.operations:
            self.window.bind(key, lambda event, operator = key: self.append_operator(operator))

        

    def create_special_buttons(self):
        self.create_clear_button()
        self.create_equals_button()
        self.create_delete_button()
        self.create_square_button()
        self.create_sqrt_button()

    def create_display_labels(self):
       total_label=tk.Label(self.display_frame, text= self.total_expression, anchor=tk.E, bg="#f5f5f5", fg="#25265E", padx=24, font=
                            ("Arial", 24))
       total_label.pack(expand=True, fill="both")

       label=tk.Label(self.display_frame, text= self.current_expression, anchor=tk.E, bg="#f5f5f5", fg="#25265E", padx=24, font=
                      ("Arial", 40, "bold"))
       label.pack(expand=True, fill="both")
            
       return total_label,label


    def create_display_frame(self):
        Frame = tk.Frame(self.window, height=221, bg="#f5f5f5")
        Frame.pack(expand=True, fill="both")
        return Frame
    
    def add_to_expressions(self, value):
        self.current_expression  = str(value)
        self.update_label()

    def create_digit_buttons(self):
        for digit,grid_value in self.digits.items():
            Button =  tk.Button(self.buttons_frame, text=str(digit), bg="#fff", fg="#25265E", font=("Arial", 24, "bold"), borderwidth=0,
                                command=lambda x=digit: self.add_to_expressions(x))
            Button.grid(row=grid_value[0], column=grid_value[1], sticky=tk.NSEW)

        def changedgt_on_hovering(event):
          global create_digit_buttons
          Button['bg']='#F0F0F0'
        
        def returndgt_to_normalstate(event):
          global create_digit_buttons
          Button['bg']='#fff'
        
        Button.bind("<Enter>", changedgt_on_hovering)
        Button.bind("<Leave>",returndgt_to_normalstate)

CodePudding user response:

To change the color of a button when the user hovers over it, simply define the activebackground option as the color you want it to be. Here is a simple example:

import tkinter

window = tkinter.Tk()
button = tkinter.Button(window, activebackground="red")
button.pack()
window.mainloop()

This turns the button red when the user hovers over it, and returns it to its original color when the user stops hovering over it.

As well as using words to specify the colors (like yellow, red, green, etc.), you can also use hexadecimal colors as well (like #ffff00, #ff0000, #0000ff, etc.).

CodePudding user response:

You can modify create_digit_buttons() as below:

    def create_digit_buttons(self):
        def changedgt_on_hovering(event):
          # use event.widget instead of hard-coded Button
          event.widget['bg']='#F0F0F0'

        def returndgt_to_normalstate(event):
          # use event.widget instead of hard-coded Button
          event.widget['bg']='#fff'

        for digit,grid_value in self.digits.items():
            Button =  tk.Button(self.buttons_frame, text=str(digit), bg="#fff", fg="#25265E", font=("Arial", 24, "bold"), borderwidth=0,
                                command=lambda x=digit: self.add_to_expressions(x))
            Button.grid(row=grid_value[0], column=grid_value[1], sticky=tk.NSEW)
            # moved the binding code inside for loop
            Button.bind("<Enter>", changedgt_on_hovering)
            Button.bind("<Leave>", returndgt_to_normalstate)
  • Related