gencoglu17
gencoglu17

Reputation: 45

Using tkinter Text widgets to display the result

I am tring to pick some 6 numbers in a range randomly and display them using Text widget.

The program is supposed to write one line every second but the output is just one line (the last line)..

Code:

from tkinter import *
import random
import time

wn=Tk()
wn.geometry("300x300")

for i in range(5):
    loto=random.sample(range(1,30),6)
    mytext=Text(wn,bg="pink",width=30,height=200)
    mytext.pack()
    mytext.insert('1.0', loto,"\n")
    mytext = mytext.get('1.0', 'end')
    time.sleep(1)

wn.mainloop()

Upvotes: 1

Views: 788

Answers (1)

Saad
Saad

Reputation: 3430

You can't use just time.sleep(1) to see update every second you have to update the main window. And you're creating like 5 Text widget every 1 seconds, one is sufficient. Just have one outside the loop and update it.

Something like this..

from tkinter import*
import random, time

wn=Tk()
wn.geometry("300x300")

mytext=Text(wn,bg="pink",width=30,height=200)
mytext.pack()

for i in range(5):
    loto = random.sample( range(1,30),6)
    mytext.insert('end', str(loto) + '\n')
    wn.update()
    time.sleep(1)

wn.mainloop()

Although, this is not the recommended way of looping something in tkinter but for small loops and these kind of purposes it is fine to use. If you plan to loop something large like updating a lot of Text, widgets and images in tkinter then use after() function ( How to use after()? ). In short after calls the function in every given interval so by putting it in a function it keeps on calling the same function till you stop it, can be stopped by different ways see this post on how to stop after.

With use of after():

from tkinter import*
import random, time

wn=Tk()
wn.geometry("300x300")

mytext=Text(wn,bg="pink",width=30,height=200)
mytext.pack()

def update(c=0):
    if c < 5:                                   # Runs 5 times
        loto = random.sample( range(1,30),6)
        mytext.insert('end', str(loto) + '\n')
        wn.after(1000, update, c+1)             # after( ms, func, args )

update()                                        # Called the function once

wn.mainloop()

Upvotes: 2

Related Questions