Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd Tkinter mouse-over behavior

Tags:

python

tkinter

I've been trying to get a mouse-over event to change the background color of a butten widget in Tkinter. I got some simple code online which works for text, but fails for color. Here it is:

from Tkinter import *
root - Tk()

b = Button(root, text='foo')
b.pack()

def enterB(event):
    b.configure(text='bar', background='red')

def leaveB(event):
    b.configure(text='foo')

b.bind('<Enter>', enterB)
b.bind('<Leave>', leaveB)

root.mainloop()

When I put my mouse over the button, the text changes to 'bar', but the background color stays gray. When my mouse leaves the area over the button, the background color changes to red, and the text changes to 'foo'. This is the opposite of what should happen.

If I put background='blue' in the b.configure statement in the leaveB function, and leave the rest the same, leaving the button will leave the button blue, and it will never be red.

Can anyone tell me what's happening?

Thanks.

like image 667
bev Avatar asked Nov 17 '12 04:11

bev


2 Answers

Firstly, I guess that's a typo on line 2, it should be root = Tk()


That program works properly for me, other than the act that on removing the mouse from the button the background stays red. Which can be changed by slightly modifying leaveB function as follows:

def leaveB(event):
    b.configure(text="foo", background="SystemButtonFace")

Where "SystemButtonFace" is the default button face color if you are on Windows

like image 187
Aditya Sriram Avatar answered Oct 22 '22 14:10

Aditya Sriram


I had the same problem (actually I was bothered with the button color not changing after a click unless you left it with the mouse). The solution was to set the activebackground color. In my understanding this is the color which is shown when the mouse is over the button (see http://www.tutorialspoint.com/python/tk_button.htm)

So what I did was:

def enterB(event):
   b.configure(text='bar', background='red')
   b.configure(activebackground='red');

This way the button already turns red when the mouse is over it. Of course you have to reset the color in the leaveB function to make it change back to grey once you left the button.

like image 2
Martin Avatar answered Oct 22 '22 14:10

Martin