Home > OS >  Python tkinter Labels stop working after some time
Python tkinter Labels stop working after some time

Time:10-14

I am new to Python and have been trying to create a dashboard that gets data from a php site in json format and then displays the data with tkinter. The application works fine for aprrox. 4 hours but after that the labels duplicate, change position and overlap and the original ones stop updating, I can see in the console that the application is still getting the json data and everything works fine except for the labels (dz, sz, iz, ssz).

How it looks when it works:
https://i.imgur.com/l5RPCJ2.png

How it looks when the labels are not working:
https://i.imgur.com/3wbLnda.png

from datetime import datetime, timedelta
from tkinter import *
import tkinter as tk
import math
import requests
import time
import subprocess


root = Tk()
root.geometry("1920x1080")
root.title("TITLE")
root.configure(background="black", cursor='none')
root.attributes('-fullscreen', True)


def updateLables(array):
    if type(array[2]) == int:
        if array[2] > 0:
            d = " "   str(array[2])
        else:
            d = array[2]
    else:
        d = array[2]

    dz = Label(root, text=str(d), anchor='e')
    sz = Label(root, text=str(array[1]), anchor='e')
    iz = Label(root, text=str(array[0]), anchor='e')
    ssz = Label(root, text=str(array[3]), anchor='e')

    iz.config(font=("Arial", 150, 'bold'), foreground="White", background="black")
    sz.config(font=("Arial", 150, 'bold'), foreground="White", background="black")
    dz.config(font=("Arial", 150, 'bold'), foreground="White", background="black")
    ssz.config(font=("Arial", 150, 'bold'), foreground="White", background="black")

    if type(array[2]) == int:
        if array[2] < 0:
            dz.config(foreground="red")
        elif array[2] >= 0:
            dz.config(foreground="green")

    sz.place(relx=0.85, rely=0.1, anchor='n', width='550', height='150')
    iz.place(relx=0.85, rely=0.3, anchor='n', width='550', height='150')
    ssz.place(relx=0.85, rely=0.5, anchor='n', width='550', height='150')
    dz.place(relx=0.85, rely=0.7, anchor='n', width='550', height='150')

    a = createjson() #Returns array with 4 int values
    root.after(5000, updateLables, a)


updateLables(createjson())

tk.mainloop()

CodePudding user response:

The main issue of your code is that it produces each iteration new Labels instead you should configure them. To be more precise, in your current code environment you should have your labels in the global namespace (where you defined your root window). This will allow you to configure them in your function and update the Labels. This way your window and your memory does not get overloaded with Labels you have no use for.

If you need further help on this issue, let me know.

  • Related