Home > OS >  Firstly I want to place label1 and after 3 seconds i want to configure background but it doesnt work
Firstly I want to place label1 and after 3 seconds i want to configure background but it doesnt work

Time:12-23

import tkinter as tk
import time
root=tk.Tk()
label1=tk.Label(text='hello',font='Calibri 25')
label1.pack()
time.sleep(3)
label1.configure(bg='green')
root.mainloop()

Again and again I say only I want to place label1 and after 3 seconds I want to change the background color but it doesnt work. Can you explain me the main problem and what can I do?

CodePudding user response:

sleep should not be used in the main tkinter loop, as this causes the interface to freeze. It's better to use after.

import tkinter as tk

COLOR = 'green'

def lbl_clear():
    label1.configure(text="", bg=root['bg'])
    

def lbl_bg(color):
    label1.configure(bg=color)
    root.after(3000, lbl_clear)


root = tk.Tk()
label1 = tk.Label(text='hello', font='Calibri 25')
label1.pack()
root.after(3000, lbl_bg, COLOR)
root.mainloop()

CodePudding user response:

So, few things to clerify here.

1. Nothing shows until main loop is running

the elements are not placed on the screen before root.mainLoop() is called, In fact - there is no screen at this point. If you do sleep(1000) for example, nothing will happened for 1000 seconds, then the screen will show with green label.

Your first lines create programmatic objects (containing data on how to be drawn on the screen, but they do nothing).

Only after calling rootMainLoop, tk creates the screen.

2. Solution: events

An event is a way of executing code when something happenes ( a button is clicked, a text is typed or for your example - a screen is created)

Please read more about events here

Implementation (pseudo code)

a way of implementing what you want:

  1. create the screen

  2. write a function that changes the label

  3. bind the function to an events that fires when label show on screen (i.e set the function to run only when the label is displayed)

     def change_color():  
         global label
         sleep(3)
         label.config(bg="green")
    
     root = tk.Tk()
    
     label = tk.Label(...)
     label.bind('<Map>',change_color)
     root.mainloop()
    

note: this example is pseudo code. not running as is

  • Related