程序源码
import turtle
from tkinter import *
from tkinter.ttk import *
import threading
def koch(size,n):
if n==0:
turtle.fd(size)
else:
for angle in [0,60,-120,60]:
turtle.left(angle)
koch(size/3,n-1)
root=Tk()
width = 300
height = 100
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth-width)/2, (screenheight-height)/2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
root.iconbitmap('.\\icon.ico')
root.title('科赫雪花')
frame1=Frame(root)
lable1=Label(frame1,text='科赫级数:')
opt=StringVar()
optionmenu1=OptionMenu(frame1,opt,'3','0','1','2','3','4','5')
def button1_clicked():
level=eval(opt.get())
root.destroy()
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200,100)
turtle.pendown()
turtle.pensize(2)
turtle.speed(10)
koch(400,level)
turtle.right(120)
koch(400,level)
turtle.right(120)
koch(400,level)
turtle.right(120)
turtle.hideturtle()
turtle.done()
button1=Button(root,text='Start',command=button1_clicked)
frame1.pack()
lable1.grid()
optionmenu1.grid(row=0,column=1)
button1.pack()
root.mainloop()
传统封包缺陷
准备好程序代码和图标文件
使用pyinstaller直接得到单个可执行程序
pyinstaller -F 科赫雪花.py -w -i icon.ico
双击运行,出错
把图标文件复制到生成的科赫雪花文件夹中
cp icon.ico .\dist\科赫雪花\
双击得到的程序,成功运行,但是启动速度非常慢,要3s~4s才可以启动,而且没有得到完美的单文件可执行程序。
总结:直接用pyinstaller得到的单个可执行程序启动速度慢,容易出bug,不方便使用资源文件
改进方案
使用pyinstaller生成可执行程序
准备好程序代码和图标
使用pyinstaller生成可执行程序
pyinstaller 科赫雪花.py -w -i icon.ico
得到了如下文件及文件夹
由于python代码中使用的是图标的相对路径,
root.iconbitmap('.\\icon.ico')
把图标复制到生成的科赫雪花文件夹中
cp icon.ico .\dist\科赫雪花\
在 .\dist\科赫雪花\ 目录得到了完整的程序
双击 科赫雪花.exe 后成功运行,可以发现程序启动用时非常短,几乎是立刻运行!
使用Enigma Virtual Box打包
把 .\dist\科赫雪花\ 目录下除了科赫雪花.exe以外的所有文件拖到Enigma Virtual Box里,然后填好待封包的主程序,如图
然后执行封包,得到
可见程序体积非常大,有19M,但启动速度比较快
测试运行
程序的启动大概用时1s
然后画一个三阶的科赫雪花:
完美运行,画出了漂亮的雪花!