【案例】什么?idle 中竟然有内置 turtle 样例?(paint)

    科技2022-07-16  139

    文章目录

    案例介绍准备工作细节设计按顺序变化颜色onscreenclick() 事件函数 代码汇总运行结果后记

    案例介绍

    我打算开启一个新的方向—— turtle 库案例。

    在我们下载安装完毕 Python3 后,在搜索(查找)框中输入 idle.exe,就能够打开系统内置的 Python 开发环境了。不知道有多少同学知道,其实在内置的开发环境中,已经内置了很多不错的 turtle 案例,对于想学习 turtle 的同学是很不错的资源。今天我们来看看其中的一个案例——paint。

    准备工作

    安装 Python3 即可,打开 idle.exe,按照下面的步骤,点击 start 就能够看到内置的样例代码了。

    细节设计

    按顺序变化颜色

    colors = ["red", "green", "blue", "yellow"] colors = colors[1:] + colors[:1]

    上面这两行代码实现了对 colors 列表中的元素轮流选择的功能。第一行是 colors 的初始化,每执行一次第二行代码,colors 列表中的元素都会按照相对顺序向后移动一位,最后一个元素移动到了第一位。

    onscreenclick() 事件函数

    onscreenclick(goto, 1) onscreenclick(changecolor, 2) onscreenclick(switchupdown, 3)

    turtle 库提供了 onscreenclick() 事件调用函数,在这个样例中,具体的定义如上面代码所示,其中第一个参数是一个方法(函数名),第二个参数是鼠标的键位(左键、中键、右键),goto 是 turtle 库内置的方法,changecolor 和 switchupdown 两个函数是我们自己编写的两个方法。

    每按下鼠标左键,当前的绘制起点就会移动到新的坐标。每按下鼠标中键,绘制颜色就会变化。每按下鼠标右键,会判断当前的笔是否已经落下,如果落下那么就执行 end_fill() 方法填充目前的区域,结束填充区域,然后抬起笔,否则落下笔,然后执行 start_fill() 方法,准备填充区域。

    代码汇总

    # coding: utf-8 # !/usr/bin/python """ @File : 小画板.py @Author : jiaming @Modify Time: 2020/10/4 18:47 @Contact : https://jiaming.blog.csdn.net/ @微信公众号答疑: codenough @Desciption : None """ """ turtle-example-suite: tdemo_paint.py A simple event-driven paint program - left mouse button moves turtle - middle mouse button changes color - right mouse button toogles betweem pen up (no line drawn when the turtle moves) and pen down (line is drawn). If pen up follows at least two pen-down moves, the polygon that includes the starting point is filled. ------------------------------------------- Play around by clicking into the canvas using all three mouse buttons. ------------------------------------------- To exit press STOP button ------------------------------------------- """ from turtle import * def switchupdown(x=0, y=0): if pen()["pendown"]: end_fill() up() else: down() begin_fill() def changecolor(x=0, y=0): global colors colors = colors[1:] + colors[:1] color(colors[0]) def main(): global colors shape("circle") resizemode("user") shapesize(.5) width(3) colors = ["red", "green", "blue", "yellow"] color(colors[0]) switchupdown() onscreenclick(goto, 1) onscreenclick(changecolor, 2) onscreenclick(switchupdown, 3) return "EVENTLOOP" if __name__ == "__main__": msg = main() print(msg) mainloop()

    运行结果

    后记

    以上就是我们这期的内容了,如果有什么问题私信我就好,下期我们将介绍内置 turtle 案例中的其它案例。

    Processed: 0.009, SQL: 8