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


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

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

turtle .onclick()

此函數用於將樂趣綁定到此 turtle 或畫布上的mouse-click事件。

用法:

turtle.onclick(fun, btn=1, add=None)

參數:

Arguments Description
fun 一個帶有兩個參數的函數,將為其分配畫布上單擊點的坐標
btn mouse-button的編號默認為1(鼠標左鍵)
add 對或錯。如果為True,則將添加新的綁定,否則,它將替換以前的綁定

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



範例1:

Python3

# import package 
import turtle 
  
  
# method to action 
def fxn(x,y):
      
    # some motion 
    turtle.right(90) 
    turtle.forward(100) 
  
# turtle speed to slowest 
turtle.speed(1) 
  
# motion 
turtle.fd(100) 
  
# allow user to click  
# for some action 
turtle.onclick(fxn)

輸出:

範例2:

Python3

# import package 
import turtle 
  
  
# screen object 
wn = turtle.Screen() 
  
# method to perform action 
def fxn(x, y):
  turtle.goto(x, y) 
  turtle.write(str(x)+","+str(y)) 
  
# onclick action  
wn.onclick(fxn) 
wn.mainloop()

輸出:




相關用法


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