Sande
Sande

Reputation: 131

Creating refreshable tkinter window without closing

I want to make a program which runs for ever and refreshes its information every 10s.

The best solution I got was:

while True:

    Gui= GUI()
    Gui.after(2000, lambda : Gui.destroy())
    Gui.mainloop()

But that resulted in the window closing and creating awful effect. Here is my code: I want to refresh the page when the json file gets modified and the window shouldn't close.

from tkinter import *
import json
import time

def openfile():
    data = []
    d={}
    return_listas = []
    with open('test.json', 'r') as f:
        for line in f:
            data.append(json.loads(line))

        for item in data:

            d.update(item)
        f.close()
        return d

class GUI(Tk):
    def __init__(self):
        self.tk = Tk()
        self.tk.wm_state('zoomed')
        self.label = {}
        self.topFrame = Frame(self.tk)
        self.topFrame.pack(side=TOP,fill=Y)
        self.task()

    def task(self):
        i = 0
        list = openfile()
        for ele in list:

            if list[ele]=="true":
                lb = Label(self.topFrame, text=ele+"\n", fg="green",font=("Helvetica", 24))
            if list[ele]=="false":
                lb = Label(self.topFrame, text=ele+"\n", fg="red",font=("Helvetica", 24))
            lb.pack(fill=X) 

            self.label[ele] = lb


        i += 1

UPDATE, now I have problem where i can't maintain refreshable information, it either stacks up or doesn't show at all

Upvotes: 0

Views: 1282

Answers (2)

Sande
Sande

Reputation: 131

All I have to do is to delete older labels

for ele in self.label:
    self.label[ele].destroy()
self.label= {}

Upvotes: 0

Stevo Mitric
Stevo Mitric

Reputation: 1619

You don't have to delete it every time, just update. Here is you GUI class:

class GUI(Tk):
    def __init__(self):
        self.tk = Tk()
        self.tk.wm_state('zoomed')
        self.topFrame = Frame(self.tk)
        self.topFrame.pack(side=TOP,fill=Y)
        self.label = Label(self.topFrame, fg="green",font=("Helvetica", 24))                    # This will be the label that is updated
        self.label.pack(fill=X) 
        self.tk.after(1000, self.task)              # in 1 second it will start the loop

    def task(self):
        list = openfile()
        for ele in list:

            if list[ele]=="true":
                self.label.configure(text = ele+"\n", fg = 'green')
            if list[ele]=="false":
                self.label.configure(text = ele+"\n", fg = 'red')

        self.tk.after(1000, self.task)              # in 1 second it will go again

gui = GUI()
gui.mainloop()

Upvotes: 1

Related Questions