python写的计算器

转移部分有可能有用的笔记

eval() 这样也不能算是计算器吧,嘿嘿 ~~( ﹁ ﹁ ) ~~~

import tkinter


# frame和entry  制作计算器

class MainForm:
    def __init__(self):
        # 设置一个页面
        self.root = tkinter.Tk()
        # 设置页面总标题
        self.root.title('啦啦啦专属')
        # 设置logo图标,格式为 .ico
        self.root.iconbitmap(r'OIP-C.ico')
        # 窗口设置
        self.win()
        # 设置背景颜色
        self.root["background"] = "orange"
        self.botton_frame()
        self.input_frame()
        # 显示页面
        self.root.mainloop()

    def win(self):
        self.screen_width = self.root.winfo_screenwidth()
        self.screen_height = self.root.winfo_screenheight()
        x = (self.screen_width - 231) / 2
        y = (self.screen_height - 280) / 2
        # 设置居中窗口
        self.root.geometry("231x280+%d+%d" % (x, y))

    def input_frame(self):
        self.inputframe = tkinter.Frame(self.root, width=20)
        self.content = tkinter.StringVar()
        self.entry = tkinter.Entry(
            self.inputframe,
            width=14,
            textvariable=self.content,
            font=(
                '微软雅黑',
                20))
        self.clean = False
        self.entry.pack(fill="x", expand=1)
        self.inputframe.pack(side="top")

    def botton_frame(self):
        self.bottonframe = tkinter.Frame(self.root, width=50)
        self.listbox = [[1, 2, 3, "+"], [4, 5, 6, "-"],
                        [7, 8, 9, "*"], [0, ".", "/", "="]]
        self.util_list = ["+", "-", "*", "/", "="]
        self.row = 0
        for num in self.listbox:
            self.column = 0
            for y in num:
                botton = tkinter.Button(
                    self.bottonframe,
                    text=y,
                    fg='black',
                    width=3,
                    font=(
                        '微软雅黑',
                        20))
                botton.bind("<Button-1>",
                            lambda event: self.button_handle(event))
                botton.grid(row=self.row, column=self.column)
                self.column += 1
            self.row += 1
        self.bottonframe.pack(side='bottom')

    def button_handle(self, event):
        oper = event.widget["text"]
        if self.clean:
            self.content.set("")
            self.clean = False
        if oper != "=":
            self.entry.insert("end", oper)
        elif oper == "=":
            # result = None
            exp = self.entry.get()
            result = eval(exp)
            self.entry.insert("end", f'={result}')
            self.clean = True

if __name__ == "__main__":
    MainForm()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值