Detailed Explanation of Python Double Version Calculator

  • 2021-10-27 08:21:54
  • OfStack

Boxed calculator

For this calculator, we use the Tkinter library that comes with Python


#  Import tkinter Library 
import tkinter

We need to do some basic operations on the window


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')

Then define an input method with a function

Input method


#  Input method 
def add(n):
    #  Get to n1 The value of the text box 
    n1 = inp.get()
    #  Empty the text box 
    inp.delete(0,len(n1))
    #  Insert the original and add the new input parameter n
    inp.insert(0,n1+str(n))

Then define a calculation method with a function

Calculation method


#  Execute calculation method 
def calc():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    #  Use the string of the text box with eval When the code executes 1 Then insert it into the text box 
    inp.insert(0,str(eval(n1)))

After finishing, we need to clear the text box. We still use the function

Clear text box method


#  Empty the text box 
def clear():
    n1 = inp.get()  
    inp.delete(0,len(n1))

After clearing the text box, there will be another character left. We need to delete the last character and still use the function

Delete last 1 character method


#  Delete the last 1 Characters 
def back():
    n1 = inp.get()  
    inp.delete(len(n1)-1,len(n1))

Then we calculate the absolute value

Calculate absolute value


#  Calculate absolute value 
def ab():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    inp.insert(0,str(eval(n1)*-1))

Set 1 text box as 1 part of button

Set the text box


#  Settings 1 Text boxes 
inp = tkinter.Entry(window, width=25)
#  In the first 0 Line, number 0 A, merge 5 Column 
inp.grid(row=0,column=0,columnspan=5)

Make one more function buttons

Function button


#  Delete button ( Window , Width, Text, Execute Command ).grid(1 Row ,0 Column )
tkinter.Button(window,width=5, text="C", command=clear).grid(row=1,column=0)
tkinter.Button(window,width=5, text=" " ", command=back).grid(row=1,column=1)
tkinter.Button(window,width=5, text="+/-", command=ab).grid(row=1,column=2)

Make operator buttons again

Operator


#  Delete button ( Window , Width, Text, Background Color, Text Color, Execute Command and Pass in Parameters ).grid(1 Row ,4 Column )
tkinter.Button(window,width=5, text="+",bg="#f70",fg="#fff",command=lambda:add("+")).grid(row=1,column=4)
tkinter.Button(window,width=5, text="-", bg="#f70",fg="#fff",command=lambda:add("-")).grid(row=2,column=4)
tkinter.Button(window,width=5, text=" × ",bg="#f70",fg="#fff",command=lambda:add("*")).grid(row=3,column=4)
tkinter.Button(window,width=5, text=" ÷ ",bg="#f70",fg="#fff",command=lambda:add("/")).grid(row=4,column=4)
tkinter.Button(window,width=12,text="0", command=lambda:add("0")).grid(row=5,column=0,columnspan=2)
tkinter.Button(window,width=5,text="=", bg="#f70",fg="#fff",command=calc).grid(row=5,column=4)
tkinter.Button(window,width=5, text=".", command=lambda:add(".")).grid(row=5,column=2)

Finally, we found that without 123 456 789 9 buttons, we created it with for loop

Add the code to the


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
0

Below

9 buttons


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
1

A box calculator is done. Please see the end of the article for the complete code

Command line calculator

The code of this calculator is very short, and you can learn it soon

First, get the first number and the second number

Acquisition number


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
2

We also have to add while True to ensure that the code is executed repeatedly, otherwise the calculator cannot operate multiple times

Add while True before


while True:
	#  Gets the number of the operation through user input 1 Number 
	num1 = int(input(" Enter the 1 Number : "))
	#  Gets the number of the operation through user input 2 Number 
	#  The default is that the string needs to be used int Convert characters to arrays 
	num2 = int(input(" Enter the 2 Number : "))
	#  Prompt the user for an operator 

So it can be repeated

Then get the operation method

Operation method


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
4

Then judge the addition

Judgement addition


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
5

Subtraction, multiplication, division and addition are similar. You can try them yourself


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
6

I really can't. You can also look at mine

The rest


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
7

And then bridge them under the addition

Bridging


while True:
	#  Gets the number of the operation through user input 1 Number 
	num1 = int(input(" Enter the 1 Number : "))
	#  Gets the number of the operation through user input 2 Number 
	#  The default is that the string needs to be used int Convert characters to arrays 
	num2 = int(input(" Enter the 2 Number : "))
	#  Prompt the user for an operator 
	print(" Input operation: 1 , adding; 2 , subtraction; 3 , multiplication; 4 , division ")
	#  Gets the arithmetic symbol entered by the user 
	choice = input(" Enter your selection (1/2/3/4):")
	#  If it is 1
	if choice == '1':
		print(num1,"+",num2,"=", num1+num2)
	#  If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1," × ",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1," ÷ ",num2,"=", num1/num2)

The algorithm part is good, we also need to add an else, otherwise the output will be wrong

else


#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
9

Finally, we add else to the bottom of Part 1 above

Bridge 2


while True:
	#  Gets the number of the operation through user input 1 Number 
	num1 = int(input(" Enter the 1 Number : "))
	#  Gets the number of the operation through user input 2 Number 
	#  The default is that the string needs to be used int Convert characters to arrays 
	num2 = int(input(" Enter the 2 Number : "))
	#  Prompt the user for an operator 
	print(" Input operation: 1 , adding; 2 , subtraction; 3 , multiplication; 4 , division ")
	#  Gets the arithmetic symbol entered by the user 
	choice = input(" Enter your selection (1/2/3/4):")
	#  If it is 1
	if choice == '1':
		print(num1,"+",num2,"=", num1+num2)
	#  If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1," × ",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1," ÷ ",num2,"=", num1/num2)
	#  Everything else is illegal 
	else:
		print(" Illegal importation ")

Both calculators have been introduced, and the complete code follows

Complete code

Boxed calculator


#  Import tkinter Library 
import tkinter
#  Get 1 Windows 
window = tkinter.Tk()
#  Set the title 
window.title(' Calculator ')
#  Set window size 
window.geometry('200x200')
#  Input method 
def add(n):
    #  Get to n1 The value of the text box 
    n1 = inp.get()
    #  Empty the text box 
    inp.delete(0,len(n1))
    #  Insert the original and add the new input parameter n
    inp.insert(0,n1+str(n))
#  Execute calculation method 
def calc():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    #  Use the string of the text box with eval When the code executes 1 Then insert it into the text box 
    inp.insert(0,str(eval(n1)))
#  Empty the text box 
def clear():
    n1 = inp.get()  
    inp.delete(0,len(n1))
#  Delete the last 1 Characters 
def back():
    n1 = inp.get()  
    inp.delete(len(n1)-1,len(n1))
#  Calculate absolute value 
def ab():
    n1 = inp.get()  
    inp.delete(0,len(n1))
    inp.insert(0,str(eval(n1)*-1))
#  Settings 1 Text boxes 
inp = tkinter.Entry(window, width=25)
#  In the first 0 Line, number 0 A, merge 5 Column 
inp.grid(row=0,column=0,columnspan=5)
#  Use for Cycle   Create  123 456 789 9 Buttons 
for i in range(0,3):
    for j in range(1,4):
      n = j+i*3
      btn=tkinter.Button(window, text=str(j+i*3),width=5, command=lambda n=n:add(n))
      btn.grid(row=i+2,column=j-1)
#  Delete button ( Window , Width, Text, Execute Command ).grid(1 Row ,0 Column )
tkinter.Button(window,width=5, text="C", command=clear).grid(row=1,column=0)
tkinter.Button(window,width=5, text=" " ", command=back).grid(row=1,column=1)
tkinter.Button(window,width=5, text="+/-", command=ab).grid(row=1,column=2)
#  Delete button ( Window , Width, Text, Background Color, Text Color, Execute Command and Pass in Parameters ).grid(1 Row ,4 Column )
tkinter.Button(window,width=5, text="+",bg="#f70",fg="#fff",command=lambda:add("+")).grid(row=1,column=4)
tkinter.Button(window,width=5, text="-", bg="#f70",fg="#fff",command=lambda:add("-")).grid(row=2,column=4)
tkinter.Button(window,width=5, text=" × ",bg="#f70",fg="#fff",command=lambda:add("*")).grid(row=3,column=4)
tkinter.Button(window,width=5, text=" ÷ ",bg="#f70",fg="#fff",command=lambda:add("/")).grid(row=4,column=4)
tkinter.Button(window,width=12,text="0", command=lambda:add("0")).grid(row=5,column=0,columnspan=2)
tkinter.Button(window,width=5,text="=", bg="#f70",fg="#fff",command=calc).grid(row=5,column=4)
tkinter.Button(window,width=5, text=".", command=lambda:add(".")).grid(row=5,column=2)
#  Enter the message loop 
window.mainloop()

Command line calculator


while True:
	#  Gets the number of the operation through user input 1 Number 
	num1 = int(input(" Enter the 1 Number : "))
	#  Gets the number of the operation through user input 2 Number 
	#  The default is that the string needs to be used int Convert characters to arrays 
	num2 = int(input(" Enter the 2 Number : "))
	#  Prompt the user for an operator 
	print(" Input operation: 1 , adding; 2 , subtraction; 3 , multiplication; 4 , division ")
	#  Gets the arithmetic symbol entered by the user 
	choice = input(" Enter your selection (1/2/3/4):")
	#  If it is 1
	if choice == '1':
		print(num1,"+",num2,"=", num1+num2)
	#  If 2
	elif choice == '2':
		print(num1,"-",num2,"=", num1-num2) 
	elif choice == '3':
		print(num1," × ",num2,"=", num1*num2) 
	elif choice == '4':
		print(num1," ÷ ",num2,"=", num1/num2)
	#  Everything else is illegal 
	else:
		print(" Illegal importation ")


Related articles: