This is an example code of my problem:
from tkinter import *
root = Tk()
def large_list():
my_list = [i for i in range(100000000)]
def make_large_list():
my_label = Label(root, text='0% completed')
my_label.pack()
large_list()
my_label2 = Label(root, text='Completed')
my_label2.pack()
my_button = Button(text='Do something', command=make_large_list)
my_button.pack()
mainloop()
The large_list()
function takes about 10 seconds to complete.
When my_button
is clicked, after waiting for 10 seconds, it displays my_label
and my_label2
on the screen at the same time, which is not what I expected. I wanted to immediately display my_label
on the screen since it was just packing a simple text label, and then, after waiting for those 10 seconds, display my_label2
on the screen since it has to go through the large_list
function.
to make it easier to undestand, I want something like this:
I tried doing the same thing without tkinter and just priting the text labels in the following code:
def large_list():
my_list = [i for i in range(100000000)]
def make_large_list():
print('0% completed')
large_list()
print('Completed')
my_input = input('Wanna do something? yes/no\n')
if my_input == 'yes':
make_large_list()
and surprisingly for me, it works exactly like I wanted. After I input 'yes'
, it prints '0% completed'
inmediatly, and after waiting 10 seconds, it prints 'Completed'
, so how can I get the same thing to work in tkinter?
CodePudding user response:
You forgot that inside make_large_list()
none of your actions update the GUI. Its only when that function ends that tkinter
takes control and processes all the changes.
Note how when you click on the button is stays in the down state and never animates back to the up state.
However, you can force tkinter
to do an update inbetween like this:
def make_large_list():
my_label = Label(root, text='0% completed')
my_label.pack()
root.update()
large_list()
my_label2 = Label(root, text='Completed')
my_label2.pack()