Teach python to package exe by hand, and package a simple small program. tkinter, python beginner. Beginner Programming Homework: Fill out your name with *

[Statement] This article may be poorly written, and the author is not skilled enough. But it must be original, must use the simplest language, and the most detailed description so that inexperienced readers can understand

[Preface] exe can be used by clicking directly on the computer. When you write a .py file, you can realize your interesting function, so you are happy to send this to your friend, but your friend does not have a ptyhon environment (environment: idle, refers to the basic python software. Or has python this software, but your program needs to use a certain module, such as pygame (a module is written by the predecessors, you can directly download it and use some simple commands to achieve powerful functions, such as pygame can make games, set windows, load Pictures, music, etc.), so we need to pack it into an exe file, so that no matter whether other people's computers have python, they can be clicked and run directly.

1. Packaging introduction:

The packaging is also a module, named pyinstaller, just install it

You can press the [win] key + R key on the desktop to enter cmd to enter cmd. Enter the command pip install pyinstaller and press Enter 

                                      ​​​​    ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        

After completion, enter pip list to view the installed module directory

pycharm can click file--setting--project. Click the plus sign here to add the pyinstaller module

 Packaging example

Second, package demo:

This is a very simple but effective example. Reference the pyttsx3 module (it can be used to make sound, which is convenient for testing, and the module needs to be downloaded by itself to further verify its executable)

Ok, let's go to the folder where mai.py is located

 

 Click here, enter cmd to enter the cmd space of this folder, you will find that the file location prefix is ​​added in front of the default line,

Just like python opens a txt document, if it is performed in a folder of the same level, only the name of the txt is required. Otherwise, the absolute address of txt is required (c/user/...)

After entering cmd, enter pyinstaller -F mai.py (change to the name of the py file)

 Prompt for successful packaging,

 

 With these files, there is an exe in the dist folder, which can be run by clicking. Other files are useless and can be deleted

important point:

1. It is possible that the Windows system will delete the program as a virus or not allow it to be opened. In the lower right corner of the security center, select the operation - allow it to appear on the device.

2. The pyinstaller -F -w -i xxx.ico xx.py command can change the icon. You need an icon website to convert your favorite picture into an ico icon file (changing the suffix name by yourself does not work)

3. The size of the package memory may be large, mainly because the package is similar to package the modules you need together, and some useless modules may be packaged, and he must use a part of the location. Not so easy to fix

4. The modules referenced by import can be used directly after packaging. If you add the following code to the line of code

try:
    f=open("add.txt", "r", encoding="utf-8").read()    # 读取add文档里的内容,以兼容中文的方式(encoding=utf-8)
    exec(f)    # 这个是成段的eval
except:
    pass            # 如果代码中有错就跳过

 In this way, you only need to change the content of add.txt to change the role of the exe program. If you want to change a certain function, you only need to send an add.txt to your friend, and it can be solved in a few kb without resending the 30MB software

3. Examples of filling text:

 Ordinary window package click is such a window, it doesn't look very good. Use the tkinter module to beautify (many tutorials)

This looks better (below)

 A friend's homework is to print out his name and fill it with *, handwriting is too tiring

You can first write in the screenshot of the name, insert the picture in the ppt to adjust the transparency, and then write in the text box *

A more advanced method is: pil can read the color of each pixel, and fill it if it is black

import tkinter as tk                   # 界面设计模块
from tkinter import filedialog         # 选择图片模块
from PIL import ImageFont              # 图片操作
from PIL import Image
from PIL import ImageDraw
import pyperclip                       # 复制到剪切板模块

Import the module first, and the last module is used to paste the result to the clipboard, which is more convenient

Here is the function that converts words to padding segments

 
 

 

 

This is a function to abbreviate text , because in python, strings can be added, and numbers can be multiplied to repeat

 

 The core function has been built, the next step is the interface design

Top, transparency, size, background, button, label, input box are all arranged

The function executed by the button is very simple . This is a direct copy text function.

We read the content of the three text boxes, and if the format is correct, change the global variables (text, font size, padding)

Otherwise, the background is marked red as a warning. Then run the core function 1. Copy to the clipboard.

 

Three.1, code:

import tkinter as tk                   # 界面设计模块
from tkinter import filedialog         # 选择图片模块
from PIL import ImageFont              # 图片操作
from PIL import Image
from PIL import ImageDraw
import pyperclip                       # 复制到剪切板模块


goal_strs = "张三"
word_size = 80
fill_item = "*"


def get_s():
    font = ImageFont.truetype("simhei.ttf", word_size)              # 写字的字体,字号
    im1 = Image.new('RGB', (len(goal_strs)*word_size, word_size), (255, 255, 255))       # 建立新图, 白底
    draw = ImageDraw.Draw(im1)                             # 写字函数
    draw.text((0, 0), goal_strs, (0, 0, 0), font=font)     # 写字,黑色

    img = im1.convert("L")
    size_x, size_y = img.size
    img = img.resize((size_x, int(size_y/2)))              # 由于最后字,每行有行间距,为了看起来正常,所以高度减半

    pix = img.load()                                       # 加载我们刚刚制作的图
    ss = ""
    for n in range(int(word_size/2)):
        for m in range(word_size*len(goal_strs)):          # 两次循环 找到整张图的每一个点
            nt = pix[m, n]                                 # 这个点对应的值
            try:
                if nt > 100:                               # 单通道结构(每个点:0-255)
                    ss += " "                              # 白色空格
                else:
                    ss += "*"                              # 黑色*号 之所以运用一个范围是可能那个点不是完全黑或者完全白
            except:
                if nt[0] > 100:                            # 多通道结构(每个点:(25, 125, 87))
                    ss += " "
                else:
                    ss += "*"

        ss += "\n"
    img.close()
    return ss                                               # 这个函数即是把给的字以这个字号填充


def str_transform_to_print_str(orig_str: str):
    srt = orig_str
    list1 = srt.split(sep="\n")                              # 按行分为列表
    list1.remove("")                                         # 减去最后一个空列表,防止后面报错
    final_str = ""
    for line_str in list1:
        s0 = line_str[0]                                     # 这是当前循环字
        ct = 1                                               # 计数
        for s in line_str[1::]:
            if s == s0:                                      # 如果这个字还是一样的,那么count+1
                ct += 1
            else:
                final_str += "{}*'{}'+".format(ct, s0)       # 否则整体加上已经重复的次数*字符,并且计数清零,字符更改
                s0 = s
                ct = 1

        final_str += "'\\n'+"
    final_str = final_str[0:-1]                             # 最后一个是加号
    return final_str


def fun1():
    tag1.config(bg="white")
    tag2.config(bg="white")
    tag3.config(bg="white")
    global goal_strs, word_size, fill_item
    count = 1
    if len(ent1.get()) > 0:
        goal_strs = ent1.get()
        count += 1
    else:
        tag1.config(bg="red")

    try:
        word_size = int(ent2.get())
        count += 1
    except:
        tag2.config(bg="red")

    if len(ent3.get()) == 1:
        fill_item = ent3.get()
        count += 1
    else:
        tag3.config(bg="red")

    if count == 4:
        next_str = get_s()
        pyperclip.copy(next_str)
        goal_strs, word_size, fill_item = "张三", 80, "*"


def fun2():
    tag1.config(bg="white")
    tag2.config(bg="white")
    tag3.config(bg="white")
    global goal_strs, word_size, fill_item
    count = 1
    if len(ent1.get()) > 0:
        goal_strs = ent1.get()
        count += 1
    else:
        tag1.config(bg="red")

    try:
        word_size = int(ent2.get())
        count += 1
    except:
        tag2.config(bg="red")

    if len(ent3.get()) == 1:
        fill_item = ent3.get()
        count += 1
    else:
        tag3.config(bg="red")

    if count == 4:
        next_str = get_s()
        fin_str = str_transform_to_print_str(next_str)
        pyperclip.copy(fin_str)
        goal_strs, word_size, fill_item = "张三", 80, "*"


def fun3():
    open_name = filedialog.askopenfilename(title='待处理 请选择', initialdir=r'D:\a', filetypes=[("", ".jpg")])
    img = Image.open(open_name)
    img = img.convert("L")
    size_x, size_y = img.size
    img = img.resize((size_x, int(size_y / 2)))

    pix = img.load()
    ss = ""
    for n in range(int(word_size / 2)):
        for m in range(word_size * len(goal_strs)):
            nt = pix[m, n]
            try:
                if nt > 100:
                    ss += " "
                else:
                    ss += "*"
            except:
                if nt[0] > 100:
                    ss += " "
                else:
                    ss += "*"

        ss += "\n"
    pyperclip.copy(ss)


root = tk.Tk()
root.attributes("-topmost", 1)
root.attributes("-alpha", 0.7)
root.geometry("400x300")
tk.Canvas(height=300, width=400, background="white").place(x=0, y=0)
root.resizable(False, False)

tag0 = tk.Label(text="提示:结果在剪切板", bg="white", font=2)
tag0.place(x=100, y=230)

tag1 = tk.Label(text="          输入:文字(勿多)          ", bg="white")
tag1.pack(pady=5)
ent1 = tk.Entry(width=20)
ent1.insert(0, "张三")
ent1.pack(pady=5)

tag2 = tk.Label(text="          输入:字号(整数)          ", bg="white")
tag2.pack(pady=5)
ent2 = tk.Entry(width=20)
ent2.insert(0, "50")
ent2.pack(pady=5)

tag3 = tk.Label(text="          输入:填充(单个)          ", bg="white")
tag3.pack(pady=5)
ent3 = tk.Entry(width=20)
ent3.insert(0, "*")
ent3.pack(pady=5)

bu1 = tk.Button(text="{}点击开始{}".format(30*" ", 30*" "), command=fun1)
bu1.pack(pady=10)
bu2 = tk.Button(text="{}获取简写{}".format(30*" ", 30*" "), command=fun2)
bu2.pack(pady=10)
bu3 = tk.Button(text="选择图片\n简单线条", command=fun3)
bu3.place(x=20, y=40)

root.mainloop()

The experiment is packaged successfully, click to use

Welcome to correct and discuss, please do not spray people

Guess you like

Origin blog.csdn.net/m0_52285505/article/details/127139335