turtle库使用——鼠标与键盘信号

turtle库使用——鼠标与键盘信号,第1张

Python的turtle模块也提供了简单的方法允许我们在Python Turtle Graphics 窗口接收鼠标按键信号,进而针对这些信号做出反应。

onclick()方法主要是在Python Turtle Graphics窗口有鼠标按键发生时,会执行参数的内容,而所放的参数是我们设计的函数:onclick(fun, btn=1, add=None)
fun是发生在onclick事件时所要执行的函数名称,它会传递按键发生的x,y位置给fun函数,btn默认是鼠标左键。

1.当在Python Turtle Graphics 窗口有按键发生时,在Python的Python Shell窗口将列出鼠标光标被按的x,y位置。

# onclick()方法主要是在Python Turtle Graphics窗口有鼠标按键发生时,会执行参数的内容,而所放的参数是我们设计的函数:
# onclick(fun, btn=1, add=None)
# fun是发生在onclick事件时所要执行的函数名称,它会传递按键发生的x,y位置给fun函数,btn默认是鼠标左键。
import turtle


def printStr(x, y):
    print(x, y)


t = turtle.Pen()
t.screen.onclick(printStr)
t.screen.mainloop()  # 一直运行直到窗口关闭才结束

使用鼠标在窗口点击,在Python的Python Shell窗口就会打印光标点击的x,y位置:

2.当在x轴大于0位置单击时,绘制半径是30的黄色圆,否则绘制半径为30的蓝色圆。

# 当在x轴大于0位置单击时,绘制半径是30的黄色圆,否则绘制半径为30的蓝色圆
import turtle


def drawSignal(x, y):
    if x > 0:
        turtle.fillcolor('yellow')
    else:
        turtle.fillcolor('blue')
    turtle.speed(15)
    turtle.penup()
    turtle.ht()
    turtle.setpos(x, y - 30)
    turtle.begin_fill()
    turtle.circle(30)
    turtle.end_fill()


t = turtle.Pen()
t.screen.onclick(drawSignal)
t.screen.mainloop()

效果:

3.onkey()和listen()

onkey()主要是关注键盘的信号,语法如下:

onkey(fun, key)  # fun是所要执行的函数,key是键盘按键

onkey()无法单独运作, 需要listen()将信号传给onkey()

单击up键海龟往上移100,单击down键海龟往下移100,单击left键海龟往左移100,单击right键海龟往右移100。

import turtle


def keyUp():
    t.seth(90)
    t.forward(100)


def keyDown():
    t.seth(270)
    t.forward(100)


def keyL():
    t.seth(180)
    t.forward(100)


def keyR():
    t.seth(0)
    t.forward(100)


t = turtle.Pen()
t.screen.onkey(keyUp, 'Up')
t.screen.onkey(keyDown, 'Down')
t.screen.onkey(keyL, 'Left')
t.screen.onkey(keyR, 'Right')
t.screen.listen()
t.screen.mainloop()

​​​​​​​

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/873811.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存