七夕来袭!是时候展现专属于程序员的浪漫了!你打算怎么给心爱的人表达爱意?鲜花礼物?代码表白?还是创意DIY?让我们一起用python画丘比特之心送给TA~
(实际还有背景音乐)
Python、mp3(这里准备的“一起学猫叫”)
完整文件下载链接见文末
(exe是打包后生成的,后面会讲)
pip install turtle pygame pyinstaller
from turtle import *
from time import sleep
from pygame import mixer
def music():
mixer.init()
mixer.music.load('Cat.mp3')
mixer.music.play()
def go_to(x, y):
up()
goto(x, y)
down()
speed_base = 5
def big_Circle(size): #函数用于绘制心的大圆
speed(0)
for i in range(150):
forward(size)
right(0.3)
def small_Circle(size): #函数用于绘制心的小圆
speed(0)
for i in range(210):
forward(size)
right(0.786)
def line(size):
speed(speed_base+1)
forward(51*size)
def heart( x, y, size):
go_to(x, y)
left(150)
begin_fill()
line(size)
big_Circle(size)
small_Circle(size)
left(120)
small_Circle(size)
big_Circle(size)
line(size)
end_fill()
def arrow():
pensize(10)
setheading(0)
speed(speed_base+1)
go_to(-400, 0)
left(15)
forward(300)
go_to(339, 178)
forward(150)
def arrowHead():
pensize(1)
speed(speed_base+5)
color('red', 'red')
begin_fill()
left(120)
forward(20)
right(150)
forward(35)
right(120)
forward(35)
right(150)
forward(20)
end_fill()
def main():
#width,height:输入宽和高为整数时,表示像素;为小数时,表示占据电脑屏幕的比例
#(startx,starty):这一坐标表示矩形窗口左上角顶点的位置,如果为空,则窗口位于屏幕中心。
setup(1.0,1.0)
pensize(2)
color('red', 'pink')
# getscreen().tracer(30, 0) #取消注释后,快速显示图案
heart(200, 0, 1) #画出第一颗心,前面两个参数控制心的位置,函数最后一个参数可控制心的大小
setheading(0) #使画笔的方向朝向x轴正方向
heart(-80, -100, 1.5) #画出第二颗心
arrow() #画出穿过两颗心的直线
arrowHead() #画出箭的箭头
speed(speed_base+1)
go_to(400, -300)
write("况小胖520", move=True, align="left", font=("楷体", 30, "normal"))
done()
if __name__ == '__main__':
music()
main()
然后运行即可:
python heart.py
如果对方没装python,那可以打包成exe给TA:
pyinstaller -F heart.py
然后在dist目录下就会生成heart.exe文件,发给TA时,记得跟mp3文件一起打包喔。
要想打包成apk,会麻烦一点。这里用的是AidLux自带的打包工具ApkBuild。
AidLux很强,以前叫AidLearning,强推,开源免费使用。
在手机上安装运行后,电脑打开浏览器即可访问AidLux,一般是ip:8000。
首先安装ApkBuild:
然后将我们的py文件和mp3文件复制到手机,浏览器输入ip:8080,要是进不去,可以手动传过去。或者去应用中心安装一下sftpgo,或者直接ssh链接传过去(端口9022,用户名root,密码aidlux)。
安装时候记得在手机环境里也装一下上面的几个库哦,很慢的话就更新下pip清华源:
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
如果顺利的话,就会给出apk的路径。(导出过程可能卡主较久,我一度以为中断了)