wonderkun's|blog

share with you!

04/20
15:03
代码控

用python的Tkinter实现一个简单的计算器

由于要开始学python的界面编程了,所以自学了一下Tkinter,发现还是挺简单的……

就用它写个简单的计算器吧@@

#!/usr/bin/python
#-*-coding:utf-8 -*-

from   Tkinter  import * 
import tkFont
import os
from functools import partial

def input(entry,value):
	entry.insert(END,value)
def  clear(entry):
	entry.delete(0,END)
def  delete(entry):
	input_len=len(entry.get())
	entry.delete(input_len-1)
def  count(entry):
	input=entry.get()
	entry.delete(0,END)
	output1="math error"
	try:
		output=str(eval(input.strip()))
	except:
		entry.insert(END,output1)
	else :
		entry.insert(END,output)
def calc():
	windows=Tk()
	windows.title('python_calc')
	
	entry_font=tkFont.Font(size=15)
	entry=Entry(windows,justify='right',font=entry_font)
	entry.grid(row=0, column=0, columnspan=4, sticky=N+W+S+E,padx=10,pady=5)  #利用entry的grid对象来摆放输入框
	
	#创建按钮的属性
	button_font = tkFont.Font(size=10, weight=tkFont.BOLD)
	button_bg='#D5E0EE'
	buttom_active_color='#7D7D7D'
	
	
	#利用偏函数创建一个mybutton函数  
	mybutton=partial(Button,windows,bg=button_bg,padx=10,pady=3,bd=2,relief='groove',activeforeground='#FFFFFF',activebackground=buttom_active_color)
	mybutton(text='7',command=lambda:input(entry,'7')).grid(row=1,column=0)
	mybutton(text='8',command=lambda:input(entry,'8')).grid(row=1,column=1)
	mybutton(text='9',command=lambda:input(entry,'9')).grid(row=1,column=2)
	mybutton(text='+',command=lambda:input(entry,'+')).grid(row=1,column=3)
	mybutton(text='4',command=lambda:input(entry,'4')).grid(row=2,column=0)
	mybutton(text='5',command=lambda:input(entry,'5')).grid(row=2,column=1)
	mybutton(text='6',command=lambda:input(entry,'6')).grid(row=2,column=2)
	mybutton(text='-',command=lambda:input(entry,'-')).grid(row=2,column=3)
	mybutton(text='1',command=lambda:input(entry,'1')).grid(row=3,column=0)
	mybutton(text='2',command=lambda:input(entry,'2')).grid(row=3,column=1)
	mybutton(text='3',command=lambda:input(entry,'3')).grid(row=3,column=2)
	mybutton(text='*',command=lambda:input(entry,'*')).grid(row=3,column=3)
	mybutton(text='0',padx=38,command=lambda:input(entry,'0')).grid(row=4,column=0,columnspan=2)
	mybutton(text='.',command=lambda:input(entry,'.')).grid(row=4,column=2)
	mybutton(text='/',command=lambda:input(entry,'/')).grid(row=4,column=3)
	mybutton(text='<-',command=lambda:delete(entry)).grid(row=5,column=0)
	mybutton(text='c',command=lambda:clear(entry)).grid(row=5,column=1)
	mybutton(text='=',padx=38,command=lambda:count(entry)).grid(row=5,column=2,columnspan=2)
	
	
	
	windows.mainloop()
	
if  __name__=='__main__':
	calc()

1