Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Tkinter Label Text Dynamically using Label.configure()

I am new to GUI development and trying to build an application using Python3.6+Tkinter.

I have a requirement where I need to change the default text (displayed by the Label when it was created) with a new text when the user hits a Button. To achieve that I am using label.configure(text="<new_text>")

To give you a simplified version of my requirement, consider following example where the Label initially displays "Welcome". When user clicks the Button, Label text should change to "Process Started" and after the process is completed the Label text should change to "Process Completed". Here do_something function runs a process which takes some time and I'm using time.sleep(5) to simulate a process that runs for 5 seconds.

from tkinter import *
from tkinter import ttk
import time

def do_something():
   label.configure(text="Process Started")
   time.sleep(5) #some process/script that takes few seconds to execute
   label.configure(text="Process Completed")

root = Tk()

label = ttk.Label(root, text="Welcome")
label.pack()
button = ttk.Button(root, text="Click to Start Process", command=do_something)
button.pack()

root.mainloop()

EXPECTED: My expectation is that when the user hits the Button, Label will display "Process Started" for 5 seconds and finally after the process completes execution, label will be updated to "Process Complete".

PROBLEM: What I see is, when I press the Button, label text changes from "Welcome" to (after 5 seconds) "Process Completed". I am unable to understand why my label is not displaying "Process Started" right after the button is pressed.

As mentioned above, I am new to GUI development and I'm learning Python and Tkinter for the first time. So I could have made some mistake in the program itself. So forgive my ignorance if I am making any basic mistake in the program flow/logic itself. I'd love to hear your thoughts, Thanks!

EDIT: As pointed out by @Rawing, there exists a similar question - Why does time.sleep pause tkinter window before it opens The basic difference, however, is that I wish to not return to mainloop before do_something function completes execution.

like image 678
MightyInSpirit Avatar asked Mar 09 '23 08:03

MightyInSpirit


1 Answers

After you change the text to "Process Started", use label.update(). That will update the text before sleeping for 5 seconds.

Tkinter does everything in its mainloop, including redrawing the text on the label. In your callback, it's not able to draw it because your callback hasn't returned yet. Calling update tells tkinter to run all the tasks it needs to on the label, even though your code is still running.

like image 73
ChristianFigueroa Avatar answered Apr 06 '23 17:04

ChristianFigueroa