📜  Python中的 turtle.onscreenclick()函数

📅  最后修改于: 2022-05-13 01:55:24.307000             🧑  作者: Mango

Python中的 turtle.onscreenclick()函数

turtle 模块以面向对象和面向过程的方式提供海龟图形原语。因为它使用 Tkinter 作为底层图形,所以它需要安装一个支持 Tk 的Python版本。

海龟.onscreenclick()

此函数用于将 fun 绑定到画布上的鼠标单击事件。

句法 :

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

参数:

Arguments      Description                                                                                                                                                  
funa function with two arguments, the coordinates of the clicked point on the canvas.
btnnumber of the mouse-button defaults to 1 (left mouse button)
addTrue or False. If True, new binding will be added, otherwise it will replace a former binding

下面是上述方法的一个例子的实现:

Python3
# import packages
import turtle
import random
  
# global colors
col = ['red', 'yellow', 'green', 'blue',
       'white', 'black', 'orange', 'pink']
  
# method to call on screen click
  
  
def fxn(x, y):
    global col
    ind = random.randint(0, 7)
      
    # set screen color randomly
    sc.bgcolor(col[ind])
  
# set screen
sc = turtle.Screen()
sc.setup(400, 300)
  
# call method on screen click
turtle.onscreenclick(fxn)


输出 :

在这里我们可以发现,每当用户在屏幕上点击(箭头上的黄色圆点)时,它都会随机改变海龟图形窗口的背景颜色。