-1

I have a GUI program such that when a button is pressed, a label should be shown that indicates some processed has started, and the process should then start. I placed all of that inside a function that gets called when the button is pressed. This causes the label to not show up right away. I think this is because the Tkinter window works in loops and the whole function must finish executing before any change is reflected in the window, is that correct? What is a good way around this?

import time
from tkinter import *

def function1():
    myLabel = Label(root, text="process started...").grid(row=6, column=3)
    time.sleep(3)
    #or some time consuming process...
root = Tk()
root.geometry("600x500")

button = Button (root, text="trial", command=function1)
button.grid(row=7, column=2)


root.mainloop()
user173729
  • 367
  • 1
  • 2
  • 8
  • First you have to understand [Event-driven programming](https://stackoverflow.com/a/9343402/7414759), [While Loop Locks Application](https://stackoverflow.com/questions/28639228/python-while-loop-locks-application) and/or [how to use after method?](https://stackoverflow.com/questions/25753632) – stovfl Mar 18 '20 at 15:48

2 Answers2

1

You can use the multithreading, threading module, to run something on a different thread. If you run it on a different thread, the Tkinter window won't wait for the whole function to finish, since that function is being run in a different thread then the Tkinter window.

  1. Import the threading module
import threading
  1. Create a function you want the new thread to run

  2. Create a new thread and pass in the function you created

thread = threading.Thread(target=function, args=arguments)

Where target is the function you want to call in this new tread, and args are the arguments you need to pass into your function (you can leave args out if there are no arguments to pass in)

  1. Run the new thread
thread.start()

Editing anything in the Tk() object must be done in the same thread it was created in (basically you can't edit anything in the same window, in 2 different threads).

DYD
  • 382
  • 2
  • 15
0

One solution is to add root.update() right after the Label (before the function).

import time
from tkinter import *

def function1():
    myLabel = Label(root, text="process started...").grid(row=6, column=3)
    root.update()  # So it will display the Label right now 
    time.sleep(3)
    # Or some time consuming process...
root = Tk()
root.geometry("600x500")

button = Button (root, text="trial", command=function1)
button.grid(row=7, column=2)


root.mainloop()

This will update the window, so you will see that Label right away.

DYD
  • 382
  • 2
  • 15