python入门——python3.7使用turtle库,蟒蛇绘制实例

文章目录

  • 一、python3.7使用turtle库
    • 1. turtle库的下载
    • 2. 修改`setup.py`文件代码
    • 3. 安装turtle
  • 二、python蟒蛇的绘制代码
    • 1. 问题分析
    • 2. 绘制的代码
    • 3. import保留字
    • 4. 程序参数的设置
    • 5. 计算问题的扩展


以下内容来自于中国慕课网中《Python语言程序设计
》课程的学习笔记。

一、python3.7使用turtle库

由于Python3.0和Python2.0在语法上存在差异,所以使用安装命令pip install turtle下载turtle库会出现错误,以下是解决方案:

1. turtle库的下载

  1. 下载地址:turtle
    python入门——python3.7使用turtle库,蟒蛇绘制实例_第1张图片
  2. 解压安装包到D:\software\turtle-0.0.2
    python入门——python3.7使用turtle库,蟒蛇绘制实例_第2张图片

2. 修改setup.py文件代码

python入门——python3.7使用turtle库,蟒蛇绘制实例_第3张图片
修改第40行代码:
python入门——python3.7使用turtle库,蟒蛇绘制实例_第4张图片

3. 安装turtle

  1. 打开cmd,输入pip install D:\software\turtle-0.0.2

  2. 报错信息Read timed out.和异常

    C:\Users\86571>pip install D:\software\turtle-0.0.2
    Processing d:\software\turtle-0.0.2
    Collecting Twisted>=8.0.1 (from turtle==0.0.2)
      Downloading https://files.pythonhosted.org/packages/5b/b1/c1944ce7c2e42afc0ee8888df118d9691c5e446cf6fbb0ec1898f2bc0bc9/Twisted-20.3.0-cp37-cp37m-win_amd64.whl (3.1MB)
    ERROR: Exception:
    Traceback (most recent call last):
      File "D:\software\Anaconda3\lib\site-packages\pip\_vendor\urllib3\response.py", line 397, in _error_catcher
        yield
      File "D:\software\Anaconda3\lib\site-packages\pip\_vendor\urllib3\response.py", line 479, in read
        data = self._fp.read(amt)
      File "D:\software\Anaconda3\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read
        data = self.__fp.read(amt)
      File "D:\software\Anaconda3\lib\http\client.py", line 457, in read
        n = self.readinto(b)
      File "D:\software\Anaconda3\lib\http\client.py", line 501, in readinto
        n = self.fp.readinto(b)
      File "D:\software\Anaconda3\lib\socket.py", line 589, in readinto
        return self._sock.recv_into(b)
      File "D:\software\Anaconda3\lib\ssl.py", line 1071, in recv_into
        return self.read(nbytes, buffer)
      File "D:\software\Anaconda3\lib\ssl.py", line 929, in read
        return self._sslobj.read(len, buffer)
    socket.timeout: The read operation timed out
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
        status = self.run(options, args)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\commands\install.py", line 345, in run
        resolver.resolve(requirement_set)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\legacy_resolve.py", line 196, in resolve
        self._resolve_one(requirement_set, req)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\legacy_resolve.py", line 359, in _resolve_one
        abstract_dist = self._get_abstract_dist_for(req_to_install)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\legacy_resolve.py", line 307, in _get_abstract_dist_for
        self.require_hashes
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\operations\prepare.py", line 199, in prepare_linked_requirement
        progress_bar=self.progress_bar
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\download.py", line 1064, in unpack_url
        progress_bar=progress_bar
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\download.py", line 924, in unpack_http_url
        progress_bar)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\download.py", line 1152, in _download_http_url
        _download_url(resp, link, content_file, hashes, progress_bar)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\download.py", line 861, in _download_url
        hashes.check_against_chunks(downloaded_chunks)
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\utils\hashes.py", line 75, in check_against_chunks
        for chunk in chunks:
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\download.py", line 829, in written_chunks
        for chunk in chunks:
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\utils\ui.py", line 156, in iter
        for x in it:
      File "D:\software\Anaconda3\lib\site-packages\pip\_internal\download.py", line 818, in resp_read
        decode_content=False):
      File "D:\software\Anaconda3\lib\site-packages\pip\_vendor\urllib3\response.py", line 531, in stream
        data = self.read(amt=amt, decode_content=decode_content)
      File "D:\software\Anaconda3\lib\site-packages\pip\_vendor\urllib3\response.py", line 496, in read
        raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
      File "D:\software\Anaconda3\lib\contextlib.py", line 130, in __exit__
        self.gen.throw(type, value, traceback)
      File "D:\software\Anaconda3\lib\site-packages\pip\_vendor\urllib3\response.py", line 402, in _error_catcher
        raise ReadTimeoutError(self._pool, None, 'Read timed out.')
    pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
    
  3. 使用代理,我用的是豆瓣的代理,命令为: pip install --index-url https://pypi.douban.com/simple

    C:\Users\86571>pip install --index-url https://pypi.douban.com/simple  D:\software\turtle-0.0.2
    Looking in indexes: https://pypi.douban.com/simple
    Processing d:\software\turtle-0.0.2
    Collecting Twisted>=8.0.1 (from turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/5b/b1/c1944ce7c2e42afc0ee8888df118d9691c5e446cf6fbb0ec1898f2bc0bc9/Twisted-20.3.0-cp37-cp37m-win_amd64.whl (3.1MB)
         |████████████████████████████████| 3.1MB 3.2MB/s
    Requirement already satisfied: PyYAML>=3.0.8 in d:\software\anaconda3\lib\site-packages (from turtle==0.0.2) (5.1.2)
    Collecting hyperlink>=17.1.1 (from Twisted>=8.0.1->turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/7f/91/e916ca10a2de1cb7101a9b24da546fb90ee14629e23160086cf3361c4fb8/hyperlink-19.0.0-py2.py3-none-any.whl
    Collecting PyHamcrest!=1.10.0,>=1.9.0 (from Twisted>=8.0.1->turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/40/16/e54cc65891f01cb62893540f44ffd3e8dab0a22443e1b438f1a9f5574bee/PyHamcrest-2.0.2-py3-none-any.whl (52kB)
         |████████████████████████████████| 61kB 4.1MB/s
    Requirement already satisfied: attrs>=19.2.0 in d:\software\anaconda3\lib\site-packages (from Twisted>=8.0.1->turtle==0.0.2) (19.2.0)
    Collecting incremental>=16.10.1 (from Twisted>=8.0.1->turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/f5/1d/c98a587dc06e107115cf4a58b49de20b19222c83d75335a192052af4c4b7/incremental-17.5.0-py2.py3-none-any.whl
    Collecting zope.interface>=4.4.2 (from Twisted>=8.0.1->turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/ef/10/62a7066db6bf7e705e9a240b60cf3263e66bbd88406858082141971239da/zope.interface-5.0.1-cp37-cp37m-win_amd64.whl (186kB)
         |████████████████████████████████| 194kB 2.2MB/s
    Collecting Automat>=0.3.0 (from Twisted>=8.0.1->turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/dd/83/5f6f3c1a562674d65efc320257bdc0873ec53147835aeef7762fe7585273/Automat-20.2.0-py2.py3-none-any.whl
    Collecting constantly>=15.1 (from Twisted>=8.0.1->turtle==0.0.2)
      Downloading https://pypi.doubanio.com/packages/b9/65/48c1909d0c0aeae6c10213340ce682db01b48ea900a7d9fce7a7910ff318/constantly-15.1.0-py2.py3-none-any.whl
    Requirement already satisfied: idna>=2.5 in d:\software\anaconda3\lib\site-packages (from hyperlink>=17.1.1->Twisted>=8.0.1->turtle==0.0.2) (2.8)
    Requirement already satisfied: setuptools in d:\software\anaconda3\lib\site-packages (from zope.interface>=4.4.2->Twisted>=8.0.1->turtle==0.0.2) (41.4.0)
    Requirement already satisfied: six in d:\software\anaconda3\lib\site-packages (from Automat>=0.3.0->Twisted>=8.0.1->turtle==0.0.2) (1.12.0)
    Building wheels for collected packages: turtle
      Building wheel for turtle (setup.py) ... done
      Created wheel for turtle: filename=turtle-0.0.2-cp37-none-any.whl size=24765 sha256=b39ec106dd82988aefe8513c9e0ecb6391eb3ad969867f75e015967f619da890
      Stored in directory: C:\Users\86571\AppData\Local\pip\Cache\wheels\58\1a\89\877c9db37a7d167b939c3ae1be66d617dd57b3ccedc341a878
    Successfully built turtle
    Installing collected packages: hyperlink, PyHamcrest, incremental, zope.interface, Automat, constantly, Twisted, turtle
    Successfully installed Automat-20.2.0 PyHamcrest-2.0.2 Twisted-20.3.0 constantly-15.1.0 hyperlink-19.0.0 incremental-17.5.0 turtle-0.0.2 zope.interface-5.0.1
    
    
  4. 运行:

    import turtle
    from datetime import *
    
    
    # 抬起画笔,向前运动一段距离放下
    def Skip(step):
        turtle.penup()
        turtle.forward(step)
        turtle.pendown()
    
    
    def mkHand(name, length):
        # 注册Turtle形状,建立表针Turtle
        turtle.reset()
        Skip(-length * 0.1)
        # 开始记录多边形的顶点。当前的乌龟位置是多边形的第一个顶点。
        turtle.begin_poly()
        turtle.forward(length * 1.1)
        # 停止记录多边形的顶点。当前的乌龟位置是多边形的最后一个顶点。将与第一个顶点相连。
        turtle.end_poly()
        # 返回最后记录的多边形。
        handForm = turtle.get_poly()
        turtle.register_shape(name, handForm)
    
    
    def Init():
        global secHand, minHand, hurHand, printer
        # 重置Turtle指向北
        turtle.mode("logo")
        # 建立三个表针Turtle并初始化
        mkHand("secHand", 135)
        mkHand("minHand", 125)
        mkHand("hurHand", 90)
        secHand = turtle.Turtle()
        secHand.shape("secHand")
        minHand = turtle.Turtle()
        minHand.shape("minHand")
        hurHand = turtle.Turtle()
        hurHand.shape("hurHand")
    
        for hand in secHand, minHand, hurHand:
            hand.shapesize(1, 1, 3)
            hand.speed(0)
    
        # 建立输出文字Turtle
        printer = turtle.Turtle()
        # 隐藏画笔的turtle形状
        printer.hideturtle()
        printer.penup()
    
    
    def SetupClock(radius):
        # 建立表的外框
        turtle.reset()
        turtle.pensize(7)
        for i in range(60):
            Skip(radius)
            if i % 5 == 0:
                turtle.forward(20)
                Skip(-radius - 20)
    
                Skip(radius + 20)
                if i == 0:
                    turtle.write(int(12), align="center", font=("Courier", 14, "bold"))
                elif i == 30:
                    Skip(25)
                    turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                    Skip(-25)
                elif (i == 25 or i == 35):
                    Skip(20)
                    turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                    Skip(-20)
                else:
                    turtle.write(int(i / 5), align="center", font=("Courier", 14, "bold"))
                Skip(-radius - 20)
            else:
                turtle.dot(5)
                Skip(-radius)
            turtle.right(6)
    
    
    def Week(t):
        week = ["星期一", "星期二", "星期三",
                "星期四", "星期五", "星期六", "星期日"]
        return week[t.weekday()]
    
    
    def Date(t):
        y = t.year
        m = t.month
        d = t.day
        return "%s %d%d" % (y, m, d)
    
    
    def Tick():
        # 绘制表针的动态显示
        t = datetime.today()
        second = t.second + t.microsecond * 0.000001
        minute = t.minute + second / 60.0
        hour = t.hour + minute / 60.0
        secHand.setheading(6 * second)
        minHand.setheading(6 * minute)
        hurHand.setheading(30 * hour)
    
        turtle.tracer(False)
        printer.forward(65)
        printer.write(Week(t), align="center",
                      font=("Courier", 14, "bold"))
        printer.back(130)
        printer.write(Date(t), align="center",
                      font=("Courier", 14, "bold"))
        printer.home()
        turtle.tracer(True)
    
        # 100ms后继续调用tick
        turtle.ontimer(Tick, 100)
    
    
    def main():
        # 打开/关闭龟动画,并为更新图纸设置延迟。
        turtle.tracer(False)
        Init()
        SetupClock(160)
        turtle.tracer(True)
        Tick()
        turtle.mainloop()
    
    
    if __name__ == "__main__":
        main()
    

    python入门——python3.7使用turtle库,蟒蛇绘制实例_第5张图片

二、python蟒蛇的绘制代码

1. 问题分析

  • 问题1: 计算机绘图是什么原理?
    一段程序为何能够产生窗体?为何能在窗体上绘制图形?
  • 问题2: Python蟒蛇绘制从哪里开始呢?
    如何绘制一条线?如何绘制一个弧形?如何绘制一个蟒蛇?

2. 绘制的代码

#pythonDraw.py
import turtle
turtle.setup(650,350,200,200) 
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
    turtle.circle(40,80)
    turtle.circle(-40,80)
turtle.circle(40,80/2)
turtle.fd(40)
turtle.circle(16,180)
turtle.fd(40*2/3)
turtle.done()

运行结果:
python入门——python3.7使用turtle库,蟒蛇绘制实例_第6张图片

3. import保留字

  • 语法:import 保留字
  • import turtle
    作用:引入一个绘图库
    这个绘图库名字叫turtle -->海龟

4. 程序参数的设置

  • Python蟒蛇的颜色:黑色、白色、七彩色…
  • Python蟒蛇的长度:1节、3节、10节…
  • Python蟒蛇的方向:向左走、斜着走…

5. 计算问题的扩展

  • Python蟒蛇绘制问题是各类图像绘制问题的代表
  • 圆形绘制、五角星绘制、国旗绘制、机器猫绘制…
  • 掌握绘制一条线的方法,就可以绘制整个世界

你可能感兴趣的:(#,Python基础语法)