Simple application of python's Tkinter library-develop a simple calculator

Develop a simple calculator using python's Tkinter library


Preface

Any mainstream language can develop a simple calculator, we will use python to develop this article! Attached source code


Tip: The following is the content of this article, the following cases are for reference

1. Experiment preparation

1. Development software selection-jupyter notebook
can write python software, I use this experiment, when you want to use jupyter notebook, you must first install anaconda, the installation tutorial is as follows Anaconda installation tutorial (graphic) but pay attention The Tsinghua source installed in Anaconda is unavailable. You need to use the Tsinghua mirror. You can check it on Baidu. There is no link here.

2. The realization of graphical interface-Tkinter

When we use python to implement the graphical interface, the package we have to use is Tkinter. Tkinter is a module for window design using python. The Tkinter module ("Tk interface") is an interface to Python's standard Tk GUI toolkit. As a specific GUI interface of python, it is an image window. Tkinter is a GUI interface that comes with python and can be edited. We can use GUI to achieve many intuitive functions. For example, if we want to develop a calculator, if it is just a program input and output In the case of windows, user experience is useless. All the development of a graphical small window is necessary. Because the language is easy to read and easy to use, this is why I choose python to be a calculator. If you want to learn more about Tkinter, you can read the detailed explanation of the big guys , with a link: Python GUI tkinter window tutorial collection

2. Development steps

1. Import the library

At this time, we need to call python's Tkinter and math packages. It should be noted that after python3, Tkinter's call'T' is capitalized ! ! ! Otherwise, the compilation will report an error.
code show as below:

import math
import tkinter as tk

2. Interface design

Program design is mainly divided into two parts, one is interface design, and the other is calculation. First, let's look at the interface design. First, we first build a framework, we can use the loop to fill in the buttons, before that we should pay attention to the calculator initialization
code as follows (example):

class Calc(tk.Tk):
    """计算器窗体类"""
    def __init__(self):
        """初始化实例"""
        tk.Tk.__init__(self)
        self.title("我的计算器")
        self.memory = 0  # 暂存数值
        self.Demo()

    def Demo(self):
        """创建界面"""
        btn_list = ["C", "(", ")", "/",
                    "7", "8", "9", "*",
                    "4", "5", "6", "-",
                    "1", "2", "3", "+",
                    "+/-", "0", ".", "="]
        r = 1
        c = 0
        for b in btn_list:
            self.button = tk.Button(self, text=b, width=5,
                                    command=(lambda x=b: self.operate(x)))
            self.button.grid(row=r, column=c, padx=3, pady=6)
            c += 1
            if c > 3:
                c = 0
                r += 1
        self.entry = tk.Entry(self, width=24, borderwidth=2,
                              bg="black", font=("黑体", 11))
        self.entry.grid(row=0, column=0, columnspan=4, padx=8, pady=6)

The next step is to implement the algorithm part. In the past, in order to realize a polynomial such as 2-(3-2) in C++ , when the polynomial is input into the calculator at once, this kind of parenthesis priority issues must be considered. You need to push numbers and symbols into the stack separately to determine the priority. When we use python, we can use the Tkinter text box (entry) to realize the usage of entry. There are many uses. You can see Python XML parsing to learn more, not here The
code is described one by one as follows:

def operate(self, key):
        """press the button"""
        if key == "=":  # 输出结果
            result = eval(self.entry.get())#获取文本框输入的值(值为=)
            self.entry.insert(tk.END, " = " + str(result))#在’=‘后输出计算结果
        elif key == "C":  # 清空输入框
            self.entry.delete(0, tk.END)#将结果清零
        elif key == "+/-":  # 取相反数
            if "=" in self.entry.get():
                self.entry.delete(0, tk.END)
            elif self.entry.get()[0] == "-":
                self.entry.delete(0)
            else:
                self.entry.insert(0, "-")
        else:  # 其他键
            if "=" in self.entry.get():
                self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, key)
if __name__ == "__main__":
    Calculator().mainloop()

3. The key-to achieve the call of the Tkinter library

Python provides multiple libraries for graphical development interfaces. The commonly used library uses Tkinter. Using Tkinter can greatly reduce the number of lines of code. The idea is clear and simple, simple and easy to read, but in the process of writing, mainly through the use of Tkinter functions , Which also makes the algorithm of the program not so prominent.


to sum up

This article only briefly introduces the use of Tkinter to develop a simple calculator. You can use the following source code, run it and try it, and attach a demonstration animation. In addition, if you are interested in the Tkinter library mentioned in this article, please see the link above, very detailed

Dynamic presentation

Source code

import tkinter as tk
class Calculator(tk.Tk):
    """计算器窗体类"""
    def __init__(self):
        """初始化实例"""
        tk.Tk.__init__(self)
        self.title("我的计算器")
        self.memory = 0  # 暂存数值
        self.Demo()
        
    def Demo(self):
        """Create the Demo"""
        btn_list = ["C", "(", ")", "/",
                    "7", "8", "9", "*",
                    "4", "5", "6", "-",
                    "1", "2", "3", "+",
                    "+/-", "0", ".", "="]
        r = 1
        c = 0
        for b in btn_list:
            self.button = tk.Button(self, text=b, width=5,
                                    command=(lambda x=b: self.operate(x)))
            self.button.grid(row=r, column=c, padx=3, pady=6)
            c += 1
            if c > 3:
                c = 0
                r += 1
        self.entry = tk.Entry(self, width=21, borderwidth=3,
                              bg="light blue", font=("黑体", 11))
        self.entry.grid(row=0, column=0, columnspan=4, padx=8, pady=6)

    def operate(self, key):
        """press the button"""
        if key == "=":  # 输出结果
            result = eval(self.entry.get())#获取文本框输入的值(值为=)
            self.entry.insert(tk.END, " = " + str(result))#在’=‘后输出计算结果
        elif key == "C":  # 清空输入框
            self.entry.delete(0, tk.END)#将结果清零
        elif key == "+/-":  # 取相反数
            if "=" in self.entry.get():
                self.entry.delete(0, tk.END)
            elif self.entry.get()[0] == "-":
                self.entry.delete(0)
            else:
                self.entry.insert(0, "-")
        else:  # 其他键
            if "=" in self.entry.get():
                self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, key)

if __name__ == "__main__":
    Calculator().mainloop()

Guess you like

Origin blog.csdn.net/weixin_44120833/article/details/110467105