I have a tk.Text() widget and a button. When the button is clicked, I want to change the text in the Text widget, then conduct a lengthy job. Here is code snippet from the button command function:
price_text.delete("1.0", tk.END)
price_text.insert(tk.END, 'PLEASE WAIT..')
result = self.the_lengthy_job()
However, the 'PLEASE WAIT..' message just won't show up until self.the_length_job() returns. Is it possible to get it show before the_length_job() starts?
---EDIT--- Here is more code:
import tkinter as tk
import pandas_datareader as web
class GUI:
def __init__(self):
self.root = tk.Tk()
self.root.geometry("800x480")
self.price_text = tk.Text(self.root)
self.price_text.grid(row=0, column=0, )
tk.Button(self.root, text="Get", command=self.do_get).grid(row=1, column=0)
self.root.mainloop()
def do_get(self):
self.price_text.delete("1.0", tk.END)
self.price_text.insert(tk.END, "PLEASE WAIT..")
result = self.lengthy_job()
def lengthy_job(self):
tickers = ["GOOG", "AAPL", "MSFT", "IBM", "F", "AMZN", "NVDA", "NFLX", "DISH", "BABA", "JD", "SHOP", "PDD", "CSCO", "AMD", "INTC", "TXN", "MU", "QCOM"]
return web.DataReader(tickers, 'yahoo', start="2020-1-1", end="2020-1-31")
GUI()
In this example, "PLEASE WAIT.." only shows up after lengthy_job() is done.
CodePudding user response:
The problem here is that the window is not being updated after the text is inserted. This is because events are only processed after a callback returns.
To force the window to process the events before the callback returns, you can call self.root.update_idletasks() (at CoolCloud's suggestion, you shouldn't use update() unless it's absolutely necessary). Here is what the do_get() should look like:
def do_get(self):
self.price_text.delete("1.0", tk.END)
self.price_text.insert(tk.END, "PLEASE WAIT..")
self.root.update_idletasks() # Update the window here
result = self.lengthy_job()
