python GUI模拟实现计算器


Posted in Python onJune 22, 2020

python编写计算器,供大家参考,具体内容如下

(1)计算器界面如下:

python GUI模拟实现计算器

(2)基本满足了计算器的所有需求,使用时不可键盘输入,只能鼠标点击左键才可执行。初始时显示0.0,每次输入的内容存于D:\num.txt(启动程序时自动创建)

(3)" AC " 记录清零返回初始 0.0;" delete " 删除上一个输入内容;" +/- " 将正数为负数,负数为正数

(4)对于不同的进制数值系统,小数的精准值不同。
因此计算机会出现 0.1+0.2=0.3000000000004 的现象
能对数据进行截断处理,可以解决问题,但精度丧失。
(此计算机没有进行截断处理)

import tkinter,os
from tkinter import *

def temp(string):#空白间隔
  temp=tkinter.Frame(string,width=20,height=50)
  temp.pack()

flag=0
node=0
def num_work():   #更新显示框Lable
  global flag
  global node
  with open("D:\\num.txt") as f:
    for length in f:
      string=length
  top_work.configure(text=string.strip('\n'))  # 重新设置标签文本
  root.after(500,num_work) # 每隔0.5s调用函数num_work自身获取结果

def num_math_int(num1,num2):#整数运算
  try:
    if num2[0]=='+':
      string=int(num1)+int(num2[1:])
    elif num2[0]=='-':
      string=int(num1)-int(num2[1:])
    elif num2[0]=='x':
      string=int(num1)*int(num2[1:])
    elif num2[0]=='/':
      string=int(num1)/int(num2[1:])
      
    with open("D:\\num.txt",'a') as f:
      f.write('\n'+str(string)+'\n')
  except:
    with open("D:\\num.txt",'a') as f:
        f.write('\n错误')
def num_math_float(num1,num2):#小数运算
  try:
    if num2[0]=='+':
      string=float(num1)+float(num2[1:])
    elif num2[0]=='-':
      string=float(num1)-float(num2[1:])
    elif num2[0]=='x':
      string=float(num1)*float(num2[1:])
    elif num2[0]=='/':
      string=float(num1)/float(num2[1:])
    if flag==0:
      with open("D:\\num.txt",'a') as f:
        f.write('\n'+str(string)+'\n')
    else:
      with open("D:\\num.txt",'a') as f:
        f.write('\n'+str(string))
  except:
    with open("D:\\num.txt",'a') as f:
        f.write('\n错误')
def decimal(num):
  if num.count('%')>0:
    num=num.replace('%','')
    num=num.replace('\n','')
    if num.isnumeric():
      num=str(float(num)/100)
    else:
      num=num[0]+str(float(num[1:])/100)
  return num
    
def work(string):#按键对应的功能
  if string.isnumeric():
    with open("D:\\num.txt","a") as file:
      file.write(string)
  else:
    #读取文件D:\\num.txt所有内容
    lists=[]
    with open("D:\\num.txt","r") as file:
      for length in file:
        lists.append(length)
          
    if string=='AC':
      with open("D:\\num.txt","w") as file:
        file.write('0.0\n')
        
    elif string=='=':
      num1=lists[-2]
      num2=lists[-1]
      if num1=='\n':#解决末尾为换行的情况
        num1=lists[-3]
        
      #将百分数小数化
      #出现结果多0.0000000001
      num1=decimal(num1)
      num2=decimal(num2)
        
      try:      #判断两个数是整数还是小数
        number=int(num1)
        number=int(num2[1:])
        num_math_int(num1,num2)#两个数进行整数运算
      except:
        num_math_float(num1,num2)#两个数进行小数运算
        
    elif string=='.':
      if lists[-1].count('.')==0:#判断结尾是否有小数点,没有写入否则报错
        with open("D:\\num.txt","a") as file:
          file.write(string)
      else:
        with open("D:\\num.txt","a") as file:
          file.write('\n错误')
          
    elif string=='+/-':
      if lists[-1].count('-')==0:#-+为-
        if lists[-1].count('+')==1:
          lists[-1]=lists[-1].replace('+','')
        lists[-1]='-'+lists[-1]
      else:           #--为+
        lists[-1]=lists[-1].replace('-','+')
      #更新文件
      with open("D:\\num.txt","w") as file:
        pass
      for length in lists:
        with open("D:\\num.txt","a") as file:
          file.write(length)
          
    elif string=='delete':
      number=lists[-1]
      lists[-1]=number[0:(len(number)-1)]#删除一位
      #更新文件
      with open("D:\\num.txt","w") as file:
        pass
      for length in lists:
        with open("D:\\num.txt","a") as file:
          file.write(length)
    elif string=='%':
      if lists[-1].endswith("%")==False:
        with open("D:\\num.txt","a") as file:
          file.write(string)
      else:
        with open("D:\\num.txt","a") as file:
          file.write('\n错误')
      
    else:
      with open("D:\\num.txt","a") as file:
        file.write('\n'+string)
  
def run():#计算器显示界面主体
  
  if os.path.exists("D:\\num.txt")==False:
    with open("D:\\num.txt",'w') as f:
      f.write('0.0\n')
      
  global root#定义全局变量root,方便Label更新
  root=tkinter.Tk()
  root.title("计算器")
  
  #x = root.winfo_screenwidth()
  #获取当前屏幕的宽
  #y = root.winfo_screenheight()
  #获取当前屏幕的高
  #print(((x-500)//2),((y-600)//2))#为居中提供的参数
  
  root.geometry('400x500+760+290')#主体长400,高500,居中
  top=tkinter.Frame(root,width=20,height=50)
  top.pack()

  global top_work#定义全局变量root
  temp(top)#空白间隔
  #计算器显示框
  top_work=tkinter.Label(top,text='',justify='left',relief=SUNKEN,bd=10,bg='white',width=40)
  top_work.pack(side='bottom')#计算器显示框(位置居下)
  num_work()
  temp(root)#空白间隔
  
  number=tkinter.Frame(root)#成放计算机键盘的容器
  number.pack()
  #所有按键,AC键为事例
  numberAC=tkinter.Button(number,text="AC",width=10,command=lambda : work('AC')).grid(row=0,column=0)
  #左键点击,执行函数work
  #按键位置(0,0)
  
  numberdelete=tkinter.Button(number,text="delete",width=10,command=lambda : work('delete')).grid(row=0,column=1)
  numberzhengfu=tkinter.Button(number,text="+/-",width=10,command=lambda : work('+/-')).grid(row=0,column=2)
  numberchu=tkinter.Button(number,text="/",width=10,command=lambda : work('/')).grid(row=0,column=3)
  
  tkinter.Button(number,text="7",width=10,command=lambda : work('7')).grid(row=1,column=0)
  tkinter.Button(number,text="8",width=10,command=lambda : work('8')).grid(row=1,column=1)
  tkinter.Button(number,text="9",width=10,command=lambda : work('9')).grid(row=1,column=2)
  tkinter.Button(number,text="x",width=10,command=lambda : work('x')).grid(row=1,column=3)
  
  tkinter.Button(number,text="4",width=10,command=lambda : work('4')).grid(row=2,column=0)
  tkinter.Button(number,text="5",width=10,command=lambda : work('5')).grid(row=2,column=1)
  tkinter.Button(number,text="6",width=10,command=lambda : work('6')).grid(row=2,column=2)
  tkinter.Button(number,text="-",width=10,command=lambda : work('-')).grid(row=2,column=3)
  
  tkinter.Button(number,text="1",width=10,command=lambda : work('1')).grid(row=3,column=0)
  tkinter.Button(number,text="2",width=10,command=lambda : work('2')).grid(row=3,column=1)
  tkinter.Button(number,text="3",width=10,command=lambda : work('3')).grid(row=3,column=2)
  tkinter.Button(number,text="+",width=10,command=lambda : work('+')).grid(row=3,column=3)
  
  tkinter.Button(number,text="%",width=10,command=lambda : work('%')).grid(row=4,column=0)
  tkinter.Button(number,text="0",width=10,command=lambda : work('0')).grid(row=4,column=1)
  tkinter.Button(number,text=".",width=10,command=lambda : work('.')).grid(row=4,column=2)
  tkinter.Button(number,text="=",width=10,command=lambda : work('=')).grid(row=4,column=3)

  root.mainloop()
if __name__=='__main__':
  run()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python字典get()方法用法分析
Apr 17 Python
PyMongo安装使用笔记
Apr 27 Python
实例探究Python以并发方式编写高性能端口扫描器的方法
Jun 14 Python
Python对数据进行插值和下采样的方法
Jul 03 Python
使用python的pexpect模块,实现远程免密登录的示例
Feb 14 Python
Django发送邮件和itsdangerous模块的配合使用解析
Aug 10 Python
python无序链表删除重复项的方法
Jan 17 Python
python加密解密库cryptography使用openSSL生成的密匙加密解密
Feb 11 Python
python 实现在无序数组中找到中位数方法
Mar 03 Python
python实现与redis交互操作详解
Apr 21 Python
基于Python中random.sample()的替代方案
May 23 Python
python不到50行代码完成了多张excel合并的实现示例
May 28 Python
keras CNN卷积核可视化,热度图教程
Jun 22 #Python
python实现斗地主分牌洗牌
Jun 22 #Python
解决Keras使用GPU资源耗尽的问题
Jun 22 #Python
Keras - GPU ID 和显存占用设定步骤
Jun 22 #Python
Python 基于jwt实现认证机制流程解析
Jun 22 #Python
python中format函数如何使用
Jun 22 #Python
Tensorflow与Keras自适应使用显存方式
Jun 22 #Python
You might like
PHP简单选择排序算法实例
2015/01/26 PHP
浅谈PDO的rowCount函数
2015/06/18 PHP
搭建Vim为自定义的PHP开发工具的一些技巧
2015/12/11 PHP
php中mkdir()函数的权限问题分析
2016/09/24 PHP
js报错 Object doesn't support this property or method的原因分析
2011/03/31 Javascript
js 固定悬浮效果实现思路代码
2013/08/02 Javascript
关闭浏览器输入框自动补齐 兼容IE,FF,Chrome等主流浏览器
2014/02/11 Javascript
jquery仿百度经验滑动切换浏览效果
2015/04/14 Javascript
关于input全选反选恶心的异常情况
2016/07/24 Javascript
JS小数转换为整数的方法分析
2017/01/07 Javascript
js通过指定下标或指定元素进行删除数组的实例
2017/01/12 Javascript
Node.js与Sails redis组件的使用教程
2017/02/14 Javascript
微信小程序获取手机号授权用户登录功能
2017/11/09 Javascript
JS基于对象的特性实现去除数组中重复项功能详解
2017/11/17 Javascript
详解关于Angular4 ng-zorro使用过程中遇到的问题
2018/12/05 Javascript
JS代码屏蔽F12,右键,粘贴,复制,剪切,选中,操作实例
2019/09/17 Javascript
用javascript实现倒计时效果
2021/02/09 Javascript
python发布模块的步骤分享
2014/02/21 Python
Python中每次处理一个字符的5种方法
2015/05/21 Python
在Django的模型和公用函数中使用惰性翻译对象
2015/07/27 Python
用Python登录好友QQ空间点赞的示例代码
2017/11/04 Python
python 读取txt中每行数据,并且保存到excel中的实例
2018/04/29 Python
python中for循环输出列表索引与对应的值方法
2018/11/07 Python
Python线性拟合实现函数与用法示例
2018/12/13 Python
Python dict和defaultdict使用实例解析
2020/03/12 Python
django rest framework serializer返回时间自动格式化方法
2020/03/31 Python
佳能德国网上商店:Canon德国
2017/03/18 全球购物
会计出纳岗位职责
2013/12/25 职场文书
护士在校生自荐信
2014/02/01 职场文书
房地产营销策划方案
2014/02/08 职场文书
公务员党员评议表自我鉴定
2014/09/14 职场文书
勿忘国耻9.18演讲稿(经典篇)
2014/09/14 职场文书
六查六看自查报告
2014/10/14 职场文书
2015年党建工作汇报材料
2015/06/25 职场文书
银行安全保卫工作总结
2015/08/10 职场文书
MySQL去除密码登录告警的方法
2022/04/20 MySQL