用Python做一個計算器

來來來,用Python做一個計算器

之前跟大家說了,我是計算機學院的,那麼,我今天就給大家展示一下我的才華吧!!!!
今天,我們要用Python的turtle模塊和math模塊製作一個簡易計算器,好了,不多說了,效果圖奉上
計算機圖片
是不是很棒棒?好了,現在,我來手把手教大家做這個程序,最後奉上全部源代碼。
現在,我們就要做一個超級無敵必不可少的步驟,那就是——是——是——是——打開編輯器。
好了,下一步就是激活模塊,代碼如下:

import math
import tkinter

然後,就要開始編寫代碼了,這個代碼呢,我們主要屬於兩個部分:計算器的構建和計算機的運行。
現在呢,我們開始我們的第一部分。
首先,我們需要構建一個探測系統,代碼如下:

root = tkinter.Tk()
root.resizable(width=False, height=False)
'''hypeparameter'''
#是否按下了運算符
IS_CALC = False
#存儲數字
STORAGE = []
#顯示框最多顯示多少個字符
MAXSHOWLEN = 18
#當前顯示的數字
CurrentShow = tkinter.StringVar()
CurrentShow.set('0')

好了,然後是判斷系統

'''按下數字鍵(0-9)'''
def pressNumber(number):
	global IS_CALC
	if IS_CALC:
		CurrentShow.set('0')
		IS_CALC = False
	if CurrentShow.get() == '0':
		CurrentShow.set(number)
	else:
		if len(CurrentShow.get()) < MAXSHOWLEN:
			CurrentShow.set(CurrentShow.get() + number)


'''按下小數點'''
def pressDP():
	global IS_CALC
	if IS_CALC:
		CurrentShow.set('0')
		IS_CALC = False
	if len(CurrentShow.get().split('.')) == 1:
		if len(CurrentShow.get()) < MAXSHOWLEN:
			CurrentShow.set(CurrentShow.get() + '.')


'''清零'''
def clearAll():
	global STORAGE
	global IS_CALC
	STORAGE.clear()
	IS_CALC = False
	CurrentShow.set('0')


'''清除當前顯示框內所有數字'''
def clearCurrent():
	CurrentShow.set('0')


'''刪除顯示框內最後一個數字'''
def delOne():
	global IS_CALC
	if IS_CALC:
		CurrentShow.set('0')
		IS_CALC = False
	if CurrentShow.get() != '0':
		if len(CurrentShow.get()) > 1:
			CurrentShow.set(CurrentShow.get()[:-1])
		else:
			CurrentShow.set('0')


'''計算答案修正'''
def modifyResult(result):
	result = str(result)
	if len(result) > MAXSHOWLEN:
		if len(result.split('.')[0]) > MAXSHOWLEN:
			result = 'Overflow'
		else:
			# 直接捨去不考慮四捨五入問題
			result = result[:MAXSHOWLEN]
	return result


'''按下運算符'''
def pressOperator(operator):
	global STORAGE
	global IS_CALC
	if operator == '+/-':
		if CurrentShow.get().startswith('-'):
			CurrentShow.set(CurrentShow.get()[1:])
		else:
			CurrentShow.set('-'+CurrentShow.get())
	elif operator == '1/x':
		try:
			result = 1 / float(CurrentShow.get())
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		IS_CALC = True
	elif operator == 'sqrt':
		try:
			result = math.sqrt(float(CurrentShow.get()))
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		IS_CALC = True
	elif operator == 'MC':
		STORAGE.clear()
	elif operator == 'MR':
		if IS_CALC:
			CurrentShow.set('0')
		STORAGE.append(CurrentShow.get())
		expression = ''.join(STORAGE)
		try:
			result = eval(expression)
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		IS_CALC = True
	elif operator == 'MS':
		STORAGE.clear()
		STORAGE.append(CurrentShow.get())
	elif operator == 'M+':
		STORAGE.append(CurrentShow.get())
	elif operator == 'M-':
		if CurrentShow.get().startswith('-'):
			STORAGE.append(CurrentShow.get())
		else:
			STORAGE.append('-' + CurrentShow.get())
	elif operator in ['+', '-', '*', '/', '%']:
		STORAGE.append(CurrentShow.get())
		STORAGE.append(operator)
		IS_CALC = True
	elif operator == '=':
		if IS_CALC:
			CurrentShow.set('0')
		STORAGE.append(CurrentShow.get())
		expression = ''.join(STORAGE)
		try:
			result = eval(expression)
		# 除以0的情況
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		STORAGE.clear()
		IS_CALC = True

第二部分:

'''Demo'''
def Demo():
	root.minsize(320, 420)
	root.title('Calculator')
	# 佈局
	# --文本框
	label = tkinter.Label(root, textvariable=CurrentShow, bg='black', anchor='e', bd=5, fg='white', font=('楷體', 20))
	label.place(x=20, y=50, width=280, height=50)
	# --第一行
	# ----Memory clear
	button1_1 = tkinter.Button(text='MC', bg='#666', bd=2, command=lambda:pressOperator('MC'))
	button1_1.place(x=20, y=110, width=50, height=35)
	# ----Memory read
	button1_2 = tkinter.Button(text='MR', bg='#666', bd=2, command=lambda:pressOperator('MR'))
	button1_2.place(x=77.5, y=110, width=50, height=35)
	# ----Memory save
	button1_3 = tkinter.Button(text='MS', bg='#666', bd=2, command=lambda:pressOperator('MS'))
	button1_3.place(x=135, y=110, width=50, height=35)
	# ----Memory +
	button1_4 = tkinter.Button(text='M+', bg='#666', bd=2, command=lambda:pressOperator('M+'))
	button1_4.place(x=192.5, y=110, width=50, height=35)
	# ----Memory -
	button1_5 = tkinter.Button(text='M-', bg='#666', bd=2, command=lambda:pressOperator('M-'))
	button1_5.place(x=250, y=110, width=50, height=35)
	# --第二行
	# ----刪除單個數字
	button2_1 = tkinter.Button(text='del', bg='#666', bd=2, command=lambda:delOne())
	button2_1.place(x=20, y=155, width=50, height=35)
	# ----清除當前顯示框內所有數字
	button2_2 = tkinter.Button(text='CE', bg='#666', bd=2, command=lambda:clearCurrent())
	button2_2.place(x=77.5, y=155, width=50, height=35)
	# ----清零(相當於重啓)
	button2_3 = tkinter.Button(text='C', bg='#666', bd=2, command=lambda:clearAll())
	button2_3.place(x=135, y=155, width=50, height=35)
	# ----取反
	button2_4 = tkinter.Button(text='+/-', bg='#666', bd=2, command=lambda:pressOperator('+/-'))
	button2_4.place(x=192.5, y=155, width=50, height=35)
	# ----開根號
	button2_5 = tkinter.Button(text='sqrt', bg='#666', bd=2, command=lambda:pressOperator('sqrt'))
	button2_5.place(x=250, y=155, width=50, height=35)
	# --第三行
	# ----7
	button3_1 = tkinter.Button(text='7', bg='#bbbbbb', bd=2, command=lambda:pressNumber('7'))
	button3_1.place(x=20, y=200, width=50, height=35)
	# ----8
	button3_2 = tkinter.Button(text='8', bg='#bbbbbb', bd=2, command=lambda:pressNumber('8'))
	button3_2.place(x=77.5, y=200, width=50, height=35)
	# ----9
	button3_3 = tkinter.Button(text='9', bg='#bbbbbb', bd=2, command=lambda:pressNumber('9'))
	button3_3.place(x=135, y=200, width=50, height=35)
	# ----除
	button3_4 = tkinter.Button(text='/', bg='#708069', bd=2, command=lambda:pressOperator('/'))
	button3_4.place(x=192.5, y=200, width=50, height=35)
	# ----取餘
	button3_5 = tkinter.Button(text='%', bg='#708069', bd=2, command=lambda:pressOperator('%'))
	button3_5.place(x=250, y=200, width=50, height=35)
	# --第四行
	# ----4
	button4_1 = tkinter.Button(text='4', bg='#bbbbbb', bd=2, command=lambda:pressNumber('4'))
	button4_1.place(x=20, y=245, width=50, height=35)
	# ----5
	button4_2 = tkinter.Button(text='5', bg='#bbbbbb', bd=2, command=lambda:pressNumber('5'))
	button4_2.place(x=77.5, y=245, width=50, height=35)
	# ----6
	button4_3 = tkinter.Button(text='6', bg='#bbbbbb', bd=2, command=lambda:pressNumber('6'))
	button4_3.place(x=135, y=245, width=50, height=35)
	# ----乘
	button4_4 = tkinter.Button(text='*', bg='#708069', bd=2, command=lambda:pressOperator('*'))
	button4_4.place(x=192.5, y=245, width=50, height=35)
	# ----取導數
	button4_5 = tkinter.Button(text='1/x', bg='#708069', bd=2, command=lambda:pressOperator('1/x'))
	button4_5.place(x=250, y=245, width=50, height=35)
	# --第五行
	# ----3
	button5_1 = tkinter.Button(text='3', bg='#bbbbbb', bd=2, command=lambda:pressNumber('3'))
	button5_1.place(x=20, y=290, width=50, height=35)
	# ----2
	button5_2 = tkinter.Button(text='2', bg='#bbbbbb', bd=2, command=lambda:pressNumber('2'))
	button5_2.place(x=77.5, y=290, width=50, height=35)
	# ----1
	button5_3 = tkinter.Button(text='1', bg='#bbbbbb', bd=2, command=lambda:pressNumber('1'))
	button5_3.place(x=135, y=290, width=50, height=35)
	# ----減
	button5_4 = tkinter.Button(text='-', bg='#708069', bd=2, command=lambda:pressOperator('-'))
	button5_4.place(x=192.5, y=290, width=50, height=35)
	# ----等於
	button5_5 = tkinter.Button(text='=', bg='#708069', bd=2, command=lambda:pressOperator('='))
	button5_5.place(x=250, y=290, width=50, height=80)
	# --第六行
	# ----0
	button6_1 = tkinter.Button(text='0', bg='#bbbbbb', bd=2, command=lambda:pressNumber('0'))
	button6_1.place(x=20, y=335, width=107.5, height=35)
	# ----小數點
	button6_2 = tkinter.Button(text='.', bg='#bbbbbb', bd=2, command=lambda:pressDP())
	button6_2.place(x=135, y=335, width=50, height=35)
	# ----加
	button6_3 = tkinter.Button(text='+', bg='#708069', bd=2, command=lambda:pressOperator('+'))
	button6_3.place(x=192.5, y=335, width=50, height=35)
	root.mainloop()


if __name__ == '__main__':
	Demo()

好了,一個259行代碼的計算器就做好了,另外,這個計算器無需下載任何插件的,界面非常整潔,最後給大家奉上滑稽:
滑稽
(網友:你這是什麼鬼????)
對不起,搞錯了哈,重來重來。
最後給大家奉上全部代碼:

'''
Function:
	tkinter計算器
Author:
	Charlie
'''
import math
import tkinter


root = tkinter.Tk()
root.resizable(width=False, height=False)
'''hypeparameter'''
# 是否按下了運算符
IS_CALC = False
# 存儲數字
STORAGE = []
# 顯示框最多顯示多少個字符
MAXSHOWLEN = 18
# 當前顯示的數字
CurrentShow = tkinter.StringVar()
CurrentShow.set('0')


'''按下數字鍵(0-9)'''
def pressNumber(number):
	global IS_CALC
	if IS_CALC:
		CurrentShow.set('0')
		IS_CALC = False
	if CurrentShow.get() == '0':
		CurrentShow.set(number)
	else:
		if len(CurrentShow.get()) < MAXSHOWLEN:
			CurrentShow.set(CurrentShow.get() + number)


'''按下小數點'''
def pressDP():
	global IS_CALC
	if IS_CALC:
		CurrentShow.set('0')
		IS_CALC = False
	if len(CurrentShow.get().split('.')) == 1:
		if len(CurrentShow.get()) < MAXSHOWLEN:
			CurrentShow.set(CurrentShow.get() + '.')


'''清零'''
def clearAll():
	global STORAGE
	global IS_CALC
	STORAGE.clear()
	IS_CALC = False
	CurrentShow.set('0')


'''清除當前顯示框內所有數字'''
def clearCurrent():
	CurrentShow.set('0')


'''刪除顯示框內最後一個數字'''
def delOne():
	global IS_CALC
	if IS_CALC:
		CurrentShow.set('0')
		IS_CALC = False
	if CurrentShow.get() != '0':
		if len(CurrentShow.get()) > 1:
			CurrentShow.set(CurrentShow.get()[:-1])
		else:
			CurrentShow.set('0')


'''計算答案修正'''
def modifyResult(result):
	result = str(result)
	if len(result) > MAXSHOWLEN:
		if len(result.split('.')[0]) > MAXSHOWLEN:
			result = 'Overflow'
		else:
			# 直接捨去不考慮四捨五入問題
			result = result[:MAXSHOWLEN]
	return result


'''按下運算符'''
def pressOperator(operator):
	global STORAGE
	global IS_CALC
	if operator == '+/-':
		if CurrentShow.get().startswith('-'):
			CurrentShow.set(CurrentShow.get()[1:])
		else:
			CurrentShow.set('-'+CurrentShow.get())
	elif operator == '1/x':
		try:
			result = 1 / float(CurrentShow.get())
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		IS_CALC = True
	elif operator == 'sqrt':
		try:
			result = math.sqrt(float(CurrentShow.get()))
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		IS_CALC = True
	elif operator == 'MC':
		STORAGE.clear()
	elif operator == 'MR':
		if IS_CALC:
			CurrentShow.set('0')
		STORAGE.append(CurrentShow.get())
		expression = ''.join(STORAGE)
		try:
			result = eval(expression)
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		IS_CALC = True
	elif operator == 'MS':
		STORAGE.clear()
		STORAGE.append(CurrentShow.get())
	elif operator == 'M+':
		STORAGE.append(CurrentShow.get())
	elif operator == 'M-':
		if CurrentShow.get().startswith('-'):
			STORAGE.append(CurrentShow.get())
		else:
			STORAGE.append('-' + CurrentShow.get())
	elif operator in ['+', '-', '*', '/', '%']:
		STORAGE.append(CurrentShow.get())
		STORAGE.append(operator)
		IS_CALC = True
	elif operator == '=':
		if IS_CALC:
			CurrentShow.set('0')
		STORAGE.append(CurrentShow.get())
		expression = ''.join(STORAGE)
		try:
			result = eval(expression)
		# 除以0的情況
		except:
			result = 'illegal operation'
		result = modifyResult(result)
		CurrentShow.set(result)
		STORAGE.clear()
		IS_CALC = True


'''Demo'''
def Demo():
	root.minsize(320, 420)
	root.title('Calculator')
	# 佈局
	# --文本框
	label = tkinter.Label(root, textvariable=CurrentShow, bg='black', anchor='e', bd=5, fg='white', font=('楷體', 20))
	label.place(x=20, y=50, width=280, height=50)
	# --第一行
	# ----Memory clear
	button1_1 = tkinter.Button(text='MC', bg='#666', bd=2, command=lambda:pressOperator('MC'))
	button1_1.place(x=20, y=110, width=50, height=35)
	# ----Memory read
	button1_2 = tkinter.Button(text='MR', bg='#666', bd=2, command=lambda:pressOperator('MR'))
	button1_2.place(x=77.5, y=110, width=50, height=35)
	# ----Memory save
	button1_3 = tkinter.Button(text='MS', bg='#666', bd=2, command=lambda:pressOperator('MS'))
	button1_3.place(x=135, y=110, width=50, height=35)
	# ----Memory +
	button1_4 = tkinter.Button(text='M+', bg='#666', bd=2, command=lambda:pressOperator('M+'))
	button1_4.place(x=192.5, y=110, width=50, height=35)
	# ----Memory -
	button1_5 = tkinter.Button(text='M-', bg='#666', bd=2, command=lambda:pressOperator('M-'))
	button1_5.place(x=250, y=110, width=50, height=35)
	# --第二行
	# ----刪除單個數字
	button2_1 = tkinter.Button(text='del', bg='#666', bd=2, command=lambda:delOne())
	button2_1.place(x=20, y=155, width=50, height=35)
	# ----清除當前顯示框內所有數字
	button2_2 = tkinter.Button(text='CE', bg='#666', bd=2, command=lambda:clearCurrent())
	button2_2.place(x=77.5, y=155, width=50, height=35)
	# ----清零(相當於重啓)
	button2_3 = tkinter.Button(text='C', bg='#666', bd=2, command=lambda:clearAll())
	button2_3.place(x=135, y=155, width=50, height=35)
	# ----取反
	button2_4 = tkinter.Button(text='+/-', bg='#666', bd=2, command=lambda:pressOperator('+/-'))
	button2_4.place(x=192.5, y=155, width=50, height=35)
	# ----開根號
	button2_5 = tkinter.Button(text='sqrt', bg='#666', bd=2, command=lambda:pressOperator('sqrt'))
	button2_5.place(x=250, y=155, width=50, height=35)
	# --第三行
	# ----7
	button3_1 = tkinter.Button(text='7', bg='#bbbbbb', bd=2, command=lambda:pressNumber('7'))
	button3_1.place(x=20, y=200, width=50, height=35)
	# ----8
	button3_2 = tkinter.Button(text='8', bg='#bbbbbb', bd=2, command=lambda:pressNumber('8'))
	button3_2.place(x=77.5, y=200, width=50, height=35)
	# ----9
	button3_3 = tkinter.Button(text='9', bg='#bbbbbb', bd=2, command=lambda:pressNumber('9'))
	button3_3.place(x=135, y=200, width=50, height=35)
	# ----除
	button3_4 = tkinter.Button(text='/', bg='#708069', bd=2, command=lambda:pressOperator('/'))
	button3_4.place(x=192.5, y=200, width=50, height=35)
	# ----取餘
	button3_5 = tkinter.Button(text='%', bg='#708069', bd=2, command=lambda:pressOperator('%'))
	button3_5.place(x=250, y=200, width=50, height=35)
	# --第四行
	# ----4
	button4_1 = tkinter.Button(text='4', bg='#bbbbbb', bd=2, command=lambda:pressNumber('4'))
	button4_1.place(x=20, y=245, width=50, height=35)
	# ----5
	button4_2 = tkinter.Button(text='5', bg='#bbbbbb', bd=2, command=lambda:pressNumber('5'))
	button4_2.place(x=77.5, y=245, width=50, height=35)
	# ----6
	button4_3 = tkinter.Button(text='6', bg='#bbbbbb', bd=2, command=lambda:pressNumber('6'))
	button4_3.place(x=135, y=245, width=50, height=35)
	# ----乘
	button4_4 = tkinter.Button(text='*', bg='#708069', bd=2, command=lambda:pressOperator('*'))
	button4_4.place(x=192.5, y=245, width=50, height=35)
	# ----取導數
	button4_5 = tkinter.Button(text='1/x', bg='#708069', bd=2, command=lambda:pressOperator('1/x'))
	button4_5.place(x=250, y=245, width=50, height=35)
	# --第五行
	# ----3
	button5_1 = tkinter.Button(text='3', bg='#bbbbbb', bd=2, command=lambda:pressNumber('3'))
	button5_1.place(x=20, y=290, width=50, height=35)
	# ----2
	button5_2 = tkinter.Button(text='2', bg='#bbbbbb', bd=2, command=lambda:pressNumber('2'))
	button5_2.place(x=77.5, y=290, width=50, height=35)
	# ----1
	button5_3 = tkinter.Button(text='1', bg='#bbbbbb', bd=2, command=lambda:pressNumber('1'))
	button5_3.place(x=135, y=290, width=50, height=35)
	# ----減
	button5_4 = tkinter.Button(text='-', bg='#708069', bd=2, command=lambda:pressOperator('-'))
	button5_4.place(x=192.5, y=290, width=50, height=35)
	# ----等於
	button5_5 = tkinter.Button(text='=', bg='#708069', bd=2, command=lambda:pressOperator('='))
	button5_5.place(x=250, y=290, width=50, height=80)
	# --第六行
	# ----0
	button6_1 = tkinter.Button(text='0', bg='#bbbbbb', bd=2, command=lambda:pressNumber('0'))
	button6_1.place(x=20, y=335, width=107.5, height=35)
	# ----小數點
	button6_2 = tkinter.Button(text='.', bg='#bbbbbb', bd=2, command=lambda:pressDP())
	button6_2.place(x=135, y=335, width=50, height=35)
	# ----加
	button6_3 = tkinter.Button(text='+', bg='#708069', bd=2, command=lambda:pressOperator('+'))
	button6_3.place(x=192.5, y=335, width=50, height=35)
	root.mainloop()


if __name__ == '__main__':
	Demo()

好了,最後,給個關注唄,不要讓我7天的成果在你的收藏裏吃灰啊!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章