Leopold2 Leopold2 - 5 months ago 99
Python Question

How to refresh the window with Tkinter

I am trying to create a window filled with random integers between 0 and 9. After a certain amount of time, the window should refresh and display new randomly selected integers. My code does the first step just fine but fails at the second part. I have looked up functions like after() but it still doesn't work. The code looks like this:

from tkinter import *
from random import *

root= Tk()
col=170
row=45
num=[[randint(0,9) for i in range(col)] for j in range(row)]

for k in range(row):
theLabel= Label(root,text=' '.join(str(e) for e in num[k]))
theLabel.pack()

def ch():
num1=[[randint(0,9) for i in range(col)] for j in range(row)]
for k in range(row):
theLabel= Label(root,text=' '.join(str(e) for e in num1[k]))
theLabel.pack()

root.after(5000,ch())
root.mainloop()


What should I do? I would appreciate any kind of help.

Answer
root.after(5000,ch())

This calls ch immediately and registers whatever the return value is to execute five seconds later. Instead, try:

root.after(5000,ch)

Edit: another problem you have is that ch adds new labels to the window, but the old ones still remain. Since you have 45 rows to start with, the new ones appear below that and will probably be off-screen, so you don't notice that they've appeared.

If you want the new numbers to replace the old, don't create a new label - just reconfigure the existing ones to have new text.

from tkinter import *
from random import *

root= Tk()
col=10
row=10
num=[[randint(0,9) for i in range(col)] for j in range(row)] 

labels = []
for k in range(row):
    theLabel= Label(root,text=' '.join(str(e) for e in num[k])) 
    theLabel.pack()
    labels.append(theLabel)

def ch():
    for label in labels:
        row = [randint(0,9) for i in range(col)]
        label.config(text = ' '.join(str(e) for e in row))

root.after(5000,ch)
root.mainloop()