简体   繁体   中英

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.

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()

Btw, this is the final working form:

from tkinter import *
from random import *

root=Tk()
col=200
row=57
num=[randint(0,9) for i in range(col*row)]
st=""

for k in range(0,col*row,col):
    st=st + ('  '.join(str(e) for e in num[k:k+col])) + '\n'

theLabel= Label(root,text=st)
theLabel.pack()

def ch():
    st1=""
    num1=[randint(0,9) for i in range(col*row)]
    for k in range(0,col*row,col):
        st1=st1 + ('  '.join(str(e) for e in num1[k:k+col])) + '\n'
    theLabel.config(text=st1)
    theLabel.pack()
    root.after(1000,ch)

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

I also added a recursion so that it goes on non-stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM