python tkinter 实现简单计算器2

本文介绍如何使用Python的tkinter模块创建一个简单的计算器,包括功能完善如除数为0的异常处理和非数字输入的异常处理。通过代码实现,展示了交互界面的实现结果,并提供了相关参考资料。
摘要由CSDN通过智能技术生成

功能完善

  1. 除法除数为0的异常处理
  2. 非数字输入的异常处理

代码实现

from tkinter import *
from tkinter.messagebox import showinfo

class Calculator(Frame):

     def keyPress(self,display):
        text_check = list(display.get())
        for i in range(len(text_check)):
            if not(text_check[i] in list(''.join('0123456789+-*/'))):
                display.set('')
                #or use 'raise SystemError("please input number or operator!")'
                showinfo(title='warning', message='please input number or operator!')
            elif('/0' in display.get()):
                display.set('')
                showinfo(title='warning', message='division by zero, please input number and operator again!')
            else:
                pass

     def __init__(self):
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title('calculator')
        self.master.rowconfigure( 0, weight = 1 )
        self.master.columnconfigure( 0, weight = 1 )
        self.grid( sticky = W+E+N+S )

        display = StringVar()

        #add entry ,use grid method
        #textvariable must use 'display' instead of 'StrinvVar()', or click button shows nothing in Entry
        entry = Entry(self, relief=SUNKEN, textvariable=display)
        #W+E+N+S means that the widget should be expanded in both directions. Default is to center the widget in the cell.
        entry.grid(row=0, column=0, columnspan=4, sticky=W+E+N+S)
        entry.bind('<KeyRelease>', lambda s=self, w=display:self.keyPress(w))

        #add button, use grid method
        grid = '789+456-123*0./='
        for index,textChar in enumerate(grid):

            a = Button(self, text=textChar, width=5, command=lambda text=textChar:display.set(display.get() + text))
            a.grid(row=1+index//4, column=index%4)
            button_text = a.cget("text")
            #print(button_text)
            if button_text == '=':
                 a.config(command=lambda:display.set(eval(display.get())))

        #add clear button
        b = Button(self, text="clear", width=20, command=lambda:display.set(""))
        b.grid(row=7, column=0, columnspan=4, sticky=W+E+N+S)


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

实现结果

  1. 输入字母a:
    这里写图片描述

  2. 除数为0:
    这里写图片描述

参考资料

python判断字符串是否包含子字符串的方法

Restricting the value in Tkinter Entry widget

How to insert only some specified characters in a tkinter Entry widget

python:tkinter弹出对话款,并获取输入框的值

TypeError: ‘type’ object is not subscriptable when indexing in to a dictionary

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值