Python中的 turtle.onclick()函数
turtle 模块以面向对象和面向过程的方式提供海龟图形原语。因为它使用 Tkinter 作为底层图形,所以它需要安装一个支持 Tk 的Python版本。
海龟.onclick()
此函数用于将 fun 绑定到此海龟或画布上的鼠标单击事件。
句法 :
turtle.onclick(fun, btn=1, add=None)
参数:Arguments Description fun a function with two arguments, to which will be assigned the coordinates of the clicked point on the canvas btn number of the mouse-button defaults to 1 (left mouse button) add True or False. If True, the new binding will be added, otherwise, it will replace a former binding
以下是上述方法的实现以及一些示例:
示例 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)
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()
输出 :
示例 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()
输出 :