Open In App

turtle.ontimer() function in Python

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

turtle.ontimer()

This function is used to install a timer, which calls fun after t milliseconds.



Syntax :

turtle.ontimer(fun, t=0)

Parameters:



Arguments  Description
fun a function with no arguments
t a number >= 0

    

Below is the implementation of the above method with an example :




# import packages
import turtle
import random
  
# global colors
col = ['red', 'yellow', 'green', 'blue',
       'white', 'black', 'orange', 'pink']
  
# method to call on timer
def fxn():
    global col
    ind = random.randint(0, 7)
  
    # set background color of the
    # turtle screen randomly
    sc.bgcolor(col[ind])
  
  
# set screen
sc = turtle.Screen()
sc.setup(400, 300)
  
# loop for timer
for i in range(10):
    turtle.ontimer(fxn, t=400*(i+1))

Output :

Here we can find that after some time (set by timer) it automatically changes the background color of the turtle graphics window randomly.

Article Tags :