1

I am currently trying to implement code into my program to update a buttons color when the user hovers the mouse cursor over it. The program recognizes the hover, but returns an error.

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1482, in __call__
    return self.func(*args)
  File "C:\Users\oiest\Documents\Programs\iNTMI\v1.1.3b\iNTMI.py", line 252, in <lambda>
    achievementsButton.bind("<Enter>", lambda event: achievementsButton.configure(bg = "red"))
  File "C:\Python34\lib\tkinter\__init__.py", line 1270, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 1261, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-bg"

I had Googled how to do the changing of colors when hovering and found the following code. Though for some reason, it does not work for me. What am I doing wrong?

    achievementsButton.bind("<Enter>", lambda event: achievementsButton.configure(bg = "red"))
    achievementsButton.bind("<Leave>", lambda event: achievementsButton.configure(bg = "white"))

This is the code from where I originally defined achievementsButton.

    achievementsButton = ttk.Button(self, text = "Achievements", command = lambda: controller.show_frame(achievements), width = "25")

1 Answers1

1

ttk.Button instances do not have a bg or background attribute. There are two solutions:

  • Use an ordinary tkinter.Button, which does have a bg attribute.
  • Keep using the ttk.Button, and configure it using a style object. See Using and customizing ttk styles for more information. Example:

 

from Tkinter import *
import ttk
root = Tk()
s = ttk.Style()
s.configure("regular.TButton", background="red")
s.configure("onhover.TButton", background="white")
button = ttk.Button(root, style="regular.TButton")
button.pack()
button.bind("<Enter>", lambda event: button.configure(style="onhover.TButton"))
button.bind("<Leave>", lambda event: button.configure(style="regular.TButton"))
root.mainloop()

However, this will only change the background color of the area behind the actual button, rather than the button's face. This post seems to indicate that it's impossible to change the face color of a ttk Button.

Community
  • 1
  • 1
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • So there is no actual way to keep the nice button design of Windows 7/8/10 using ttk? That's a little disappointing, but you did help me. Thank you. –  Aug 03 '15 at 13:23