How to use Sleep for a Tkinter graphical interface loading effect

Asked

Viewed 324 times

0

I’m willing to use the Sleep module team provides a load/wait effect on checking a condition. No use of Tkinter, the effect works perfectly, however, when I try to do the same with the Label of Tkinter, That doesn’t work anymore. Would anyone know why? follows an example code below:

from tkinter import *
from time import sleep

# Janela qualquer
janela = Tk()

# Variáveis com valores hipotéticos
a = 12
b = 15

lb_relacao_vh = Label(janela, font=("Century Gothic", 10, "bold"), bd=5,
                    text="Verificando a relação vão/altura.", anchor="w")
lb_relacao_vh.grid(row=0, column=0, sticky=W)
sleep(1)
lb_relacao_vh['text'] = "Verificando a relação vão/altura.."
sleep(1)
lb_relacao_vh['text'] = "Verificando a relação vão/altura..."

if a > b:
   lb_relacao_vh['fg'] = 'red'
   lb_relacao_vh['text'] = 'Verificando a relação vão/altura...ERRO!'
else:
   lb_relacao_vh['fg'] = 'green'
   lb_relacao_vh['text'] = 'Verificando a relação vão/altura...OK!'


janela.mainloop()
  • The sleep() generates a lock in the execution of the code, so that this does not occur you must execute the sleep() asynchronously. In Python some options are multiprocessing, threading or asyncio. I had a similar problem when I needed to generate a chart (Example) who kept updating himself.

  • Hello @Renatocruz I don’t understand very well how I can apply this in my example (I’m learning on my own and so I don’t understand some things)

1 answer

0


Basically the Python interpreter is reading line by line of your code, when it reaches the line of sleep() it stands still until the time that has been spent is over (notice that the window does not open).

After Sleep() time ends he:

  • Configure the widget.
  • Does the verification of if.
  • Get in the mainloop() now the window is created and displayed, however the widget is already ready.

To avoid this the interface should be created at the same time as we do the sleep(), configuration and verification (if), so the code must be asynchronous (in this case).

Based on your code and without making major changes or paradigm shift, I came to this code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Código assíncrono (threading)"""

import threading
import tkinter as tk
from time import sleep

# Janela qualquer (main window)
janela = tk.Tk()

# Variáveis com valores hipotéticos
a = 12
b = 15

# Criando o widget.
lb_relacao_vh = tk.Label(janela, font=("Century Gothic", 10, "bold"), bd=5,
                         text="Verificando a relação vão/altura.", anchor=tk.W)
# Posicionando o widget na janela.
lb_relacao_vh.grid(row=0, column=0, sticky=tk.W)


# Método que será executado de forma assíncrona.
def verificar_altura():
    lb_relacao_vh['text'] = "Verificando a relação vão/altura."
    sleep(1)
    lb_relacao_vh['text'] = "Verificando a relação vão/altura.."
    sleep(1)
    lb_relacao_vh['text'] = "Verificando a relação vão/altura..."
    sleep(1)

    if a > b:
        lb_relacao_vh['fg'] = 'red'
        lb_relacao_vh['text'] = 'Verificando a relação vão/altura...ERRO!'
    else:
        lb_relacao_vh['fg'] = 'green'
        lb_relacao_vh['text'] = 'Verificando a relação vão/altura...OK!'


# Executando o método em um thead do processador diferente daquele onde está o loop da janela.
threading.Thread(target=verificar_altura, daemon=True).start()

# Loop que fica repetindo a janela (FPS).
janela.mainloop()

If this is not the idea goes commenting so we can refine the code or even locate other possibilities.

  • I tested the code you suggested and it really worked, however, I would like to take the opportunity to ask one more question: in codes of more than one conditioning structure in which the condition uses data from the previous one and between the execution of these, I would like to implement the waiting time. In the following style: Check1... Ok; Check2... Ok and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.