Python+tkinter使用40行代码实现计算器功能

yipeiwu_com6年前Python基础

本文实例为大家分享了40行Python代码实现计算器功能,供大家参考,具体内容如下

偶尔用脚本写点东西也是不错的。

效果图

代码

from tkinter import * 
reset=True 
def buttonCallBack(event): 
 global label 
 global reset 
 num=event.widget['text'] 
 if num=='C': 
  label['text']="0" 
  return 
 if num in "=": 
  label['text']=str(eval(label['text'])) 
  reset=True 
  return 
 s=label['text'] 
 if s=='0' or reset==True: 
  s="" 
  reset=False 
 label['text']=s+num 
#主窗口 
root=Tk() 
root.wm_title("计算器") 
#显示栏1 
label=Label(root,text="0",background="white",anchor="e") 
label['width']=35 
label['height']=2 
label.grid(row=1,columnspan=4,sticky=W) 
#按钮 
showText="789/456*123-0.C+" 
for i in range(4): 
 for j in range(4): 
  b=Button(root,text=showText[i*4+j],width=7) 
  b.grid(row=i+2,column=j) 
  b.bind("<Button-1>",buttonCallBack) 
showText="()" 
for i in range(2): 
 b=Button(root,text=showText[i],width=7) 
 b.grid(row=6,column=2+i) 
 b.bind("<Button-1>",buttonCallBack) 
b=Button(root,text="=") 
b.grid(row=6,columnspan=2,sticky="we") 
b.bind("<Button-1>",buttonCallBack) 
root.mainloop() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用pickle模块实现序列化功能示例

本文实例讲述了Python使用pickle模块实现序列化功能。分享给大家供大家参考,具体如下: Python内置的pickle模块能够将Python对象序列成字节流,也可以把字节流反序列...

Python中用post、get方式提交数据的方法示例

前言 最近在使用Python的过程中,发现网上很少提到在使用post方式时,怎么传一个数组作为参数的示例,此处根据自己的实践经验,给出相关示例,下面话不多说了,来一起跟着小编学习学习吧。...

python 读取txt,json和hdf5文件的实例

一.python读取txt文件 最简单的open函数: # -*- coding: utf-8 -*- with open("test.txt","r",encoding="gbk"...

PyQt5组件读取参数的实例

1.QLineEdit QLineEdit.text() #输出str类型 2.QCheckBox QCheckBox.checkState() #状态 选定: int(QCh...

python实现的用于搜索文件并进行内容替换的类实例

本文实例讲述了python实现的用于搜索文件并进行内容替换的类。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python -O # coding: UTF-8 "...