Maria
Maria

Reputation: 117

how to display constantly random numbers tkinter

How to display random numbers in canvas that the number changes constantly.

from tkinter import *
from random import randrange
from tkinter.font import *
root=Tk()
root.geometry("600x300")
while True:
    var=randrange(0,10)
    var+=60
cv = Canvas(root,width=200,height=200,bg="blue")
styles = Font(family="calibri",size=30,weight="bold")
cv.create_text(100,100,text="Number: "+str(var),font=styles,fill="lightblue")
cv.pack(side=RIGHT)
root.mainloop()

I want the efect of random nums lile in this code, but in tkinter canvas

from random import randrange
from time import sleep
from os import system

while True:
    system("cls")
    rand = randrange(10)
    rand+=60
    print("Random number: ",rand)
    sleep(1)

Upvotes: 2

Views: 658

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15088

Take a look at this example, that uses randint and after().

from tkinter import *
import random
#from tkinter.font import *

root = Tk()
root.geometry("600x300")


def repeat():
    global timer
    rand = random.randint(1, 100)
    # configuring the tag, to overcome over writing of text.
    cv.itemconfigure('rand', text="Number: "+str(rand))
    # asking to repeat it, you can change the interval.
    timer = root.after(1000, repeat)

def stop():
    root.after_cancel(timer)

cv = Canvas(root, width=200, height=200, bg="blue")
#styles = Font(family="calibri",size=30,weight="bold")
cv.create_text(100, 100, font=("calibri", 20, "bold"),
               fill="lightblue", tag='rand')  # added a tag
cv.pack()

b_start = Button(root, text='Start', command=repeat,width=10)
b_start.pack(pady=10)

b_stop = Button(root, text='Stop', command=stop,width=10)
b_stop.pack(padx=10)

root.mainloop()

Changes:

  • A while loop might cause the window to become unresponsive, hence ive used after() method here to repeat a function constantly, if you have any plans of cancelling the after() calls, let me know. You can adjust the time between each call by adjusting ms.

  • Here I have also used randint instead of randrange() hope it serves the same purpose for this need too.

  • And also i have removed the import of tkinter.font as there is no need to import a module and can specify the fonts in tuple like ("calibri",30,"bold")

Why use after() and not while?

This is because a while loop might interfere a tkinter mainloop() causing the window to be unresponsive at times, so it is not recommended to use while or time.sleep(). Instead you could use the built-in after() method by tkinter or threading too.

Here is a bit more on after():

  • It takes two positional arguments,mainly, ms and func
  • ms - It is the time(in milliseconds) after which the specified function will be triggered.
  • func - It is the function to be triggered after the specified ms finishes.

Hope this cleares your doubts, do let me know if any errors.

Cheers

Upvotes: 1

Related Questions