0

I'm working on a custom button for a list, and want to make it change color when the mouse hovers above the button. See the following code for how I'm trying to do it:

import tkinter as tk
from tkinter import *

class list_button:
    def __init__(self, container, text, font_size):
        self.list_button = tk.Button(container, text=text, font = ("helvatica", (0 + font_size)), relief = "flat")
        self.list_button.pack()
        self.list_button.bind('<Enter>', self.enter_func(self))
        self.list_button.bind('<Leave>', self.leave_func(self))

    def enter_func(self, key):
        print("Enter")
        self.list_button.configure(bg = "grey")
    
    def leave_func(self, key):
        print("Leave")
        self.list_button.configure(bg = "white")

root = tk.Tk()

for i in range(10):
    list_button(root, i, 15)

root.mainloop()

What seems to happen is that the code calls the function once and then unbinds the function. What am I doing wrong here?

  • 3
    You are calling the functions immediately, and binding their return values (which are None) to the event. You just want to reference the function, not call it - `self.enter_func` for example, with no parentheses. – jasonharper Apr 15 '21 at 19:19
  • @jasonharper Thanks! that fixed the issue. Shows that I have a lot to learn about classes, I didn't know they I could call them without (self). – thekingoflorda Apr 15 '21 at 19:22
  • (self) is an implicit parameter – Alan Apr 15 '21 at 19:32

1 Answers1

0

For people that are stuck on the same problem. This is the revised code:

import tkinter as tk
from tkinter import *

class list_button:
    def __init__(self, container, text, font_size):
        self.list_button = tk.Button(container, text=text, font = ("helvatica", (0 + font_size)), relief = "flat")
        self.list_button.pack()
        self.list_button.bind('<Enter>', self.enter_func)
        self.list_button.bind('<Leave>', self.leave_func)

    def enter_func(self, key):
        print("Enter")
        self.list_button.configure(bg = "grey")
    
    def leave_func(self, key):
        print("Leave")
        self.list_button.configure(bg = "white")

root = tk.Tk()

for i in range(10):
    list_button(root, i, 15)

root.mainloop()

The changes are in the following part:

self.list_button.bind('<Enter>', self.enter_func)
self.list_button.bind('<Leave>', self.leave_func)