當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python turtle.ontimer()用法及代碼示例

turtle 模塊以麵向對象和麵向過程的方式提供 turtle 圖形基元。由於它使用Tkinter作為基礎圖形,因此需要安裝有Tk支持的Python版本。

turtle .ontimer()

此函數用於安裝計時器,該計時器在t毫秒後調用fun。

用法:

turtle.ontimer(fun, t=0)

參數:

參數 Description
fun 沒有參數的函數
t > = 0的數字



下麵是上述方法的實現示例:

Python3

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

輸出:

在這裏我們可以發現,經過一段時間(由計時器設置),它會自動隨機更改 turtle 圖形窗口的背景顏色。

相關用法


注:本文由純淨天空篩選整理自deepanshu_rustagi大神的英文原創作品 turtle.ontimer() function in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。