2
votes

Is there a best practice for making a tkinter button momentarily change color when it is selected (so the user gets a visual feedback that the button was pressed).

I have read it is not a good idea to use time.sleep() in a tkinter GUI.

When my button is pressed, the code happens so fast that even when I have a button.config() command to change color, it doesn't occur without using time.sleep()

Any suggestions?

2

2 Answers

2
votes

I think this may be what you want:

Button(background=normal_color, foreground=text_color,
       activebackground=pressed_color, activeforeground=pressed_text_color)

This changes the button from normal_color to pressed_color when the button is pressed.

It's actually a simple question with a simple answer but I had to look everywhere too. Finally found this answer by reading http://effbot.org/tkinterbook/button.htm.

0
votes

You can change the color upon clicking, then use the after method to reset the color back to the original, after some time has passed

import tkinter as tk


def reset_color():
    bt['fg'] = 'black'


def clickme():
    print('clicked')
    bt['fg'] = 'red'
    root.after(2000, reset_color)  # after 2 seconds


root = tk.Tk()
bt = tk.Button(root, text='will color for a while\nafter clicked', command=clickme)
bt.pack()
root.mainloop()