当前位置:   article > 正文

用python简单代码做一个计算器_python计算器代码

python计算器代码

python简单代码做一个计算器

import tkinter as tk


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

    def create(self):
        """创建界面"""
        btn_list = ["C", "M->", "->M", "/",
                    "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.click(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="yellow", font=("Consolas", 12))
        self.entry.grid(row=0, column=0, columnspan=4, padx=8, pady=6)

    def click(self, key):
        """响应按钮"""
        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 == "->M":  # 存入数值
            self.memory = self.entry.get()
            if "=" in self.memory:
                ix = self.memory.find("=")
                self.memory = self.memory[ix + 2:]
            self.title("M=" + self.memory)
        elif key == "M->":  # 取出数值
            if self.memory:
                self.entry.insert(tk.END, self.memory)
        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__":
    Calc().mainloop()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

结果展示:
在这里插入图片描述

小编在这里是用jupyter 运行成功的。
有什么问题可以在评论中指出哦,小编会一一回答你们的。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/814828
推荐阅读
相关标签
  

闽ICP备14008679号