zoukankan      html  css  js  c++  java
  • Python学习之旅(三十二)

    Python基础知识(31):图形界面(Ⅱ)

    Python内置了turtle库,可以在计算机上绘图

    运动控制:

    1、画笔定位到坐标(x,y):turtle.goto(x,y)

    2、向正方向运动 distance 长的距离:turtle.forward(distance)

    3、向负方向运动 distance 长的距离:turtle.backward(distance)

    4、向右偏angle度:turtle.right(angle)

    5、向左偏angle度:turtle.left(angle)

    6、回到原点:turtle.home()

    7、画圆形以radius为半径,extent为圆的角度:turtle.circle(radius, extent=None, steps=None)

    8、以speed速度运动:turtle.speed(speed)

    一、简单的长方形

    width()函数可以设置笔刷宽度,pencolor()函数可以设置颜色

    #导入turtle包的所有内容
    from turtle import *
    
    #设置笔刷宽度
    width(5)
    
    #前进
    forward(200)
    #右转90度
    right(90)
    
    #笔刷颜色
    pencolor('red')
    forward(100)
    right(90)
    
    pencolor('green')
    forward(200)
    right(90)
    
    pencolor('blue')
    forward(100)
    right(90)
    
    #调用done()使得窗口等待被关闭,否则将立即关闭窗口
    done()

    运行上述代码,会自动弹出一个绘图窗口,然后绘制出一个长方形

    二、用正方形画圆

    60 个正方形每隔 1 度排列,短短几行代码可以生成一个漂亮规则的图形

    import turtle
    for i in range(360):
    turtle.setheading(i)
    for i in range(4):
    turtle.forward(100)
    turtle.left(90)

    执行完这个程序大概要几分钟的时间,效果图如下

    三、绘制一棵分型树

    使用递归绘制一棵分型树

    from turtle import *
    
    # 设置色彩模式是RGB:
    colormode(255)
    
    lt(90)
    
    lv = 14
    l = 120
    s = 45
    
    width(lv)
    
    # 初始化RGB颜色:
    r = 0
    g = 0
    b = 0
    pencolor(r, g, b)
    
    penup()
    bk(l)
    pendown()
    fd(l)
    
    def draw_tree(l, level):
        global r, g, b
        # save the current pen width
        w = width()
    
        # narrow the pen width
        width(w * 3.0 / 4.0)
        # set color:
        r = r + 1
        g = g + 2
        b = b + 3
        pencolor(r % 200, g % 200, b % 200)
    
        l = 3.0 / 4.0 * l
    
        lt(s)
        fd(l)
    
        if level < lv:
            draw_tree(l, level + 1)
        bk(l)
        rt(2 * s)
        fd(l)
    
        if level < lv:
            draw_tree(l, level + 1)
        bk(l)
        lt(s)
    
        # restore the previous pen width
        width(w)
    
    speed("fastest")
    
    draw_tree(l, 4)
    
    done()

    运行大概要几分钟的时间,效果图如下

    参考资料:

    1、廖雪峰学习官网:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001542537415495bc2748dc8ceb4d3890301cf8235e3728000

    2、不会飞的章鱼:https://www.cnblogs.com/OctoptusLian/p/6363354.html

    3、海龟绘图简易教程|Turtle for Python:https://blog.csdn.net/u013468614/article/details/82622497

  • 相关阅读:
    一年来把自己从学.Net到用.Net,收集的资料共享出来B/s中的存储过程(二)
    收集的.Net文章(十五)ASP.NET 2.0 Caching For performance
    收集的.Net文章(十六)SQL Server日期计算
    P.V操作原语和信号量
    2004年2008年系分论文题目整理,考SA的可以看一下
    2010年个人总结
    MASM,NASM和AT&T汇编格式备注
    Unity Application Block 学习笔记之一使用配置文件
    Javascript 学习笔记之String类测试
    javascript学习笔记之Object类型测试
  • 原文地址:https://www.cnblogs.com/finsomway/p/10113467.html
Copyright © 2011-2022 走看看