效果展示
代码详解
2.1 导入库
2.2 播放音乐
2.3 定义画小仓鼠头的函数
2.4 定义画左眼右眼的函数
2.5 定义画嘴的函数

在介绍代码之前,先来看下本文的实现效果。
可以参考Pinstaller(Python打包为exe文件)一文把Python文件转化成exe,发给未安装Python的他/她。

1 导入库
首先导入本文需要加载的库,如果你有些库还没有安装,导致运行代码时报错,可以在Anaconda Prompt中用pip方法安装。
# -*- coding: UTF-8 -*-'''代码用途 :画小仓鼠作者 :阿黎逸阳博客 : https://blog.csdn.net/qq_32532663/article/details/106176609'''import osimport pygameimport turtle as t
本文应用到的库较少,只应用了os、pygame和turtle三个库。
os库可以设置文件读取的位置。
pygame库是为了绘制过程更有趣,在绘图过程中添加了背景音乐。
turtle库是绘图库,相当于给你一支画笔,你可以在画布上用数学逻辑控制的代码完成绘图。
2 播放音乐
接着应用pygame库播放背景音乐,本文的音乐是《Eran - 春の思い出》。
#播放音乐print('播放音乐')pygame.mixer.init()pygame.mixer.music.load(r"F:\公众号\64.小仓鼠\Eran - 春の思い出.mp3")pygame.mixer.music.set_volume(0.5)pygame.mixer.music.play(1, 10)
如果选择播放音乐,需要在代码music.load函数中把你想放音乐的电脑本地存放地址填进去。
有部分朋友对这一块有疑问,填充格式可参考如下图片:

3 定义画小仓鼠头的函数
然后设置画板的大小,并定义绘制小仓鼠头的函数。
t.title('阿黎逸阳的代码公众号')t.speed(10)#t.screensize(1000, 800)t.setup(startx=0, starty = 0, width=800, height = 600)print('画右耳朵')#画右耳朵t.penup()t.goto(100, 150)t.pendown()t.pensize(0.5)t.color('cornsilk')#t.color('cornsilk', 'cornsilk')t.begin_fill()t.setheading(40)t.circle(40, 20)t.circle(7, 180)t.right(22)t.circle(50, 12)print('画头')#画头t.setheading(173)t.circle(200, 14)print('画左耳朵')#画左耳朵t.setheading(120)t.circle(40, 20)t.circle(7, 180)t.right(22)t.circle(50, 12)print('画左脸')#画左脸t.setheading(230)t.circle(200, 10)t.setheading(190)t.circle(20, 100)print('画脸上的波浪线')#画脸上的波浪线t.setheading(60)t.circle(-30, 100)t.setheading(60)t.circle(-10, 130)t.setheading(70)t.circle(-10, 130)t.setheading(40)t.circle(-38, 100)t.setheading(56)t.circle(20, 130)t.setheading(110)t.circle(80, 22)t.end_fill()
关键代码详解:
t.pensize(width):设置画笔的尺寸。
t.color(color):设置画笔的颜色。
t.penup():抬起画笔,一般用于另起一个地方绘图使用。
t.goto(x,y):画笔去到某个位置,参数为(x,y),对应去到的横坐标和纵坐标。
t.pendown():放下画笔,一般和penup组合使用。
t.left(degree):画笔向左转多少度,括号里表示度数。
t.right(degree):画笔向右转多少度,括号里表示度数。
t.circle(radius,extent,steps):radius指半径,若为正,半径在小乌龟左侧radius远的地方,若为负,半径在小乌龟右侧radius远的地方;extent指弧度;steps指阶数。
画外轮廓的关键是:通过调节circle函数中的半径和弧度来调节曲线的弧度,从而使得小仓鼠的轮廓比较流畅。
4 定义画左眼和右眼的函数
接着定义画左眼和右眼的函数。
print('画左眼睛')#画左眼睛t.penup()t.goto(30, 115)t.pendown()t.color('black')t.begin_fill()t.setheading(5)t.circle(-20, 40)t.setheading(60)t.circle(6, 205)t.end_fill()print('画右眼睛')#画右眼睛t.penup()t.goto(90, 116)t.pendown()t.color('black')t.begin_fill()t.setheading(180)t.circle(20, 40)t.setheading(120)t.circle(-6, 205)t.end_fill()
5 定义画嘴的函数
接着定义画嘴的函数。
#画嘴巴t.color('black', 'yellow')t.begin_fill()t.setheading(-20)t.circle(10, 60)t.setheading(290)t.circle(-30, 30)t.circle(-9, 180)t.left(20)t.circle(-50, 12)t.setheading(-22)t.circle(10, 60)t.end_fill()
至此,在Python中实现小仓鼠的绘制逻辑已大致讲解完毕。


扫一扫关注我
13162366985
投稿微信号、手机号