LuGibs
LuGibs

Reputation: 190

Change a label's text colour, change back on keypress

I want to change a label's text colour, wait a few seconds, then change it back when I press a key.

My end goal is making a full onscreen keyboard that will highlight the key that you pressed. However I can't get the function to pause between turning text blue, then back to black. I attempted using time.sleep(2), but it appears to do that at the start of the function, as opposed to the order I wrote it in.

from tkinter import *
import time

window = Tk()

window.geometry("1000x700")

LabQ = Label(window,text="Q",font=("Courier", 30))

LabQ.place(x=210,y=260)

def key(event):
    LabQ = Label(window,text="Q",fg="ROYALBLUE",font=("Courier", 30))
    LabQ.place(x=210,y=260)
    time.sleep(2)
    LabQ = Label(window,text="Q",font=("Courier", 30))
    LabQ.place(x=210,y=260)

window.bind("<key>", key)

window.mainloop()

Upvotes: 2

Views: 2360

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

You have two problems. One is that you're not changing the color, you're creating an entirely new widget. To change the color you need to use the configure method on an existing widget.

Second, when you call sleep that's exactly what the GUI does -- it sleeps. No code is running and the screen can't be refreshed. As a general rule of thumb, a GUI should never call sleep.

The solution is to use use after to schedule the change for some point in the future:

def key(event):
    bg = LabQ.cget("background")
    LabQ.configure(background="royalblue")
    LabQ.after(2000, lambda color=bg: LabQ.configure(background=color))

This example doesn't gracefully handle the case where you type the same key twice in under two seconds, but that's unrelated to the core issue of how to change the value after a period of time has elapsed.

Upvotes: 3

Related Questions