The tkinter module in python makes a small software for 24 points

A few days ago, in order to practice the tkinter module, I wanted to find a practical example to practice. I happened to write a python script of 24 points in the previous blog post. It just happens that I will take you to practice.
If you want to make a small software, you need two steps:
First, you need to write the code.
Second, the package code is a small software (.exe). The
code is as follows:

#coding: utf-8
from tkinter import Tk, Entry, StringVar, Label, Button, Menu #在导入模块的时候尽量只导入自己用的函数,这样在打包的时候包体会小一些
from itertools import permutations
from tkinter.messagebox import showinfo

window = Tk() #创建窗口
window.title("秒算24点") #窗口标题
window.resizable(0, 0) #窗口大小
#window.iconbitmap(".\\net.ico") #更换图标,图标格式是.ico,放在跟代码同一个目录下面即可使用

entry = Entry(window, width=15, show=None) #创建输入文本框
entry.grid(row=0, column=1, columnspan=1)
var = StringVar()

## 输出标签(显示结果)
lable1 = Label(window, textvariable=var, bg="CornflowerBlue", width=20, height=2, font=("Arial", 12))
lable1.grid(row=3, column=0, columnspan=10)

expression = []
flag = ""
Status = False
dict_expression = {
    
    }
ClickNextNumber = 0
def Calculate24():
    global expression, flag, Status, dict_expression, ClickNextNumber
    nums = tuple(entry.get().split(" "))
    Status = False

    if len(nums) != 4:
        var.set("输入有误,建议查看帮助!")
        expression.clear()
        dict_expression.clear()
    else:
        ## 下面需要进行数学算术计算,所以需要将字符串转化为int
        num1, num2, num3, num4 = nums
        num1, num2, num3, num4 = int(num1), int(num2), int(num3), int(num4)

        ## 创建列表:输入的数字存放在一个列表,数字的排序方式一个列表,运算符号一个列表,一个空列表list2用来存放正确的表达式
        list1 = [num1, num2, num3, num4]
        ConstituteList = [element for element in permutations(list1)]  # 利用permutations()方法获取四个数字所有的排序方式
        symbols = ["+", "-", "*", "/"]
        list2 = []  # 存放算出结果为24的排列组合的列表
        flag = False

        # 将每一组4个数字的排序做for循环,计算所有添加运算符号的结果
        for N in ConstituteList:
            num1, num2, num3, num4 = N
            for s1 in symbols:
                for s2 in symbols:
                    for s3 in symbols:
                        if s1 + s2 + s3 == "+++" or s1 + s2 + s3 == "***":
                            # 最大数为13,所以只会出现两种情况不需要加括号,分别为"+", "*"
                            ArithmeticalExpressions = ["%s %s %s %s %s %s %s" % (num1, s1, num2, s2, num3, s3, num4)]
                        else:
                            ArithmeticalExpressions = [
                                "((%s %s %s) %s %s) %s %s" % (num1, s1, num2, s2, num3, s3, num4),
                                "(%s %s %s) %s (%s %s %s)" % (num1, s1, num2, s2, num3, s3, num4),
                                "(%s %s (%s %s %s)) %s %s" % (num1, s1, num2, s2, num3, s3, num4),
                                "%s %s ((%s %s %s) %s %s)" % (num1, s1, num2, s2, num3, s3, num4),
                                "%s %s (%s %s (%s %s %s))" % (num1, s1, num2, s2, num3, s3, num4)]

                        for ArithmeticalExpression in ArithmeticalExpressions:
                            try:
                                if eval(ArithmeticalExpression) == 24:
                                    list2.append(ArithmeticalExpression + " = 24")
                                    flag = True
                            except ZeroDivisionError:  # 0是不能作为除数的,当0为除数时会报错,所以这里需要用到异常处理
                                pass
        expression = list(set(list2))
        dict_expression = dict(enumerate(expression))

        if flag == False:
            var.set("无法算出24")
        else:
            var.set(expression[0])
            ClickNextNumber = 0
            Status = True

def Next_item():
    global flag, Status, ClickNextNumber
    if len(expression) != 0 or flag == False:
        if var.get() == "前面没有了哦!": #判断var.get()的值,因为如果是从"这已经是最前面的一条了哦!"返回到下一条,ClickNextNumber的值需要从0开始
            ClickNextNumber = 0
        else:
            if ClickNextNumber < len(expression):
                ClickNextNumber += 1

        if ClickNextNumber < len(dict_expression): #当ClickNextNumber等于dict_expression的长度的时候,dict_expression[ClickNextNumber]为空
            var.set(expression[ClickNextNumber])
        else:
            if ClickNextNumber == len(dict_expression):
                var.set("后面没有了哦!")
    else:
        if Status == False:
            var.set("检查一下您的输入哦!")

def Previous():
    global Status, dict_expression, ClickNextNumber
    if var.get() != "输入有误,建议查看帮助!":
        if Status == True or flag == False:
            if ClickNextNumber > 0:
                ClickNextNumber -= 1
                var.set(dict_expression[ClickNextNumber])
            else:
                var.set("前面没有了哦!")
        else:
            var.set("检查一下您的输入哦!")
    else:
        var.set("检查一下您的输入哦!")

def print_help():
    help = " 1.规则:输入4个整数,每一个整数大于0且不超过13(程序逻辑上来说输入的只要是整数就可以了,这方面没有做控制),程序会自动进行运算,将能输出结果为24的正确的表达式显示在屏幕上。\n \
2.输入数字的时候请注意空格,在数字前后都不能有空格,数字之间只能有一个空格而且必须以空格隔开,例如:1 2 3 4。"
    showinfo(title='Help', message=help)

def About():
    about="Author: WYP\nVersion: test\nProduction background: Studying\nThis is a small program for calculating 24 dots. I hope you have a good time"
    showinfo(title='About', message=about)

## 布局
button1 = Button(window, text="Last", bg="Tomato", width=11, height=1, command=Previous) #按键1
button2 = Button(window, text="计算", bg="LightSeaGreen", width=11, height=1, command=Calculate24) #按键2
button3 = Button(window, text="Next", bg="Tomato", height=1, width=11, command=Next_item)

button1.grid(row=2, column=0)
button2.grid(row=2, column=1)
button3.grid(row=2, column=2)

## 菜单(menu)
menu = Menu(window)
submenu = Menu(menu, tearoff=0)
submenu.add_command(label='Help')
menu.add_command(label='Help', command=print_help)
submenu1 = Menu(menu, tearoff=0)
submenu1.add_command(label='About')
menu.add_command(label='About', command=About)
window.config(menu=menu, bg="PaleTurquoise")

window.mainloop()

After writing the code, use the pyinstaller tool to package the code into an .exe executable file
1. Open the cmd command of windows and install pyinstaller
pip install pyinstaller on the computer
2. Install pywin32
pip install pywin32
3. You can switch to the directory where the code is located (or Do not switch, but be optimistic about which directory the generated .exe file is located in)
cd /d "The path where the code is located"
4 It is
recommended not to use the -F option for compiling and packaging , and the .exe executable file generated by the -F single degree is opened in the open It is basically more than 5 seconds
pyinstaller -D -w Calculation24.py

The commonly used options of pyinstaller are as follows:
-F: only generate a single exe format file after packaging (not recommended);
-D: default option, create a directory containing exe files and a large number of dependent files (recommended);
-c: default option , Use the console (the black box similar to cmd) (use as appropriate);
-w: do not use the console (use as the case may be);
-p: add the search path to let it find the corresponding library (use as the case);
-i: change the icon icon of the generated program (use as appropriate);

Take a look at the output effect:
1. After running, a window will automatically pop up
Insert picture description here
2. Enter and click to calculate
Insert picture description here
3. You can view the previous expression and the next expression
Insert picture description here
4. The input format is incorrect
Insert picture description here
5. The help window will automatically pop up
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44901564/article/details/106903315