Reputation: 545
I am having an issue with the portion of code below:
my_var = tk.StringVar(value="start")
my_label = tk.Label(self.root, textvariable=my_var)
def my_method(input):
my_var.set("working")
#make a method call to an external Python API; can take a few mins to finish
my_var.set("complete")
tk.Button(self.root, text="GO!", command=lambda: my_method(input))
I have a button that, when clicked, should execute my_method
which should initially change the text in my_label
to working
, process some actions in an external API, then update the label to complete
. What is actually happening is my_method
is called, the label's text DOES NOT change, the API call is made which takes a few mins, then my label is updated to complete
. I am assuming that it processes both the set commands quickly, but I only see the final set value.
Is there a reason why this is happening (have I done something wrong) and is there a solution to it? If this is expected behaviour, could someone explain why it is the case?
Whilst writing this, I thought about maybe launching a thread to execute the initial set call to see if that will work. I'd prefer a simpler solution though.
Upvotes: 1
Views: 89
Reputation: 18921
Tkinter needs you to return promptly from the callback, so that it can get back to the processing it needs to be doing in Tk.mainloop. Without being able to do this processing, it can't update your label's text. (Nor can it handle normal processing events like dragging the window, etc.)
The callbacks should never hang onto the main thread for long periods of time, as a result. If there's some time-consuming processing to do for them, it should be done in a separate thread.
Upvotes: 3