Learn to Program 22 : Python Calculator

preview_player
Показать описание


In this part of the Learn to Program series we make a working calculator from start to finish in one video. We create a Use Case Description to figure out exactly what must occur in the program step-by-step. We then create a calculator object, convert the use case into code, create the GUI interface using TkInter and end with homework you should solve to improve your programming abilities.

Thank you to Patreon supports like the following for helping me make this video

@kyleaisho
@thetwistedhat
vjFaLk
Рекомендации по теме
Комментарии
Автор

Wow you've been programming for 30+ years, that's amazing!

petersonic
Автор

this channel is a heavy heavy source of information,
I'm happy I found it

lutic
Автор

If you use the eval() function, you can make a simple calculator in less than 50-60 lines!

themindstorm
Автор

It's unbelievable how many things one person is capable of!

HighTechSoftware
Автор

i just edited it with google calculator design... i only changed gui :d i cant make them work but maybe you can... it will be good practice


from tkinter import *
from tkinter import ttk
import math

class Calculator:
# Stores the current value to display in the entry
calc_value = 0.0

# Will define if this was the last math button clicked
div_trigger = False
mult_trigger = False
add_trigger = False
sub_trigger = False

# Called anytime a number button is pressed
def button_press(self, value):

# Get the current value in the entry
entry_val = self.number_entry.get()

# Put the new value to the right of it
# If it was 1 and 2 is pressed it is now 12
# Otherwise the new number goes on the left
entry_val += value

# Clear the entry box
self.number_entry.delete(0, "end")

# Insert the new value going from left to right
self.number_entry.insert(0, entry_val)

# Returns True or False if the string is a float
def isfloat(self, str_val):
try:

# If the string isn't a float float() will throw a
# ValueError
float(str_val)

# If there is a value you want to return use return
return True
except ValueError:
return False

# Handles logic when math buttons are pressed
def math_button_press(self, value):

# Only do anything if entry currently contains a number
if

# make false to cancel out previous math button click
self.add_trigger = False
self.sub_trigger = False
self.mult_trigger = False
self.div_trigger = False

# Get the value out of the entry box for the calculation
self.calc_value = float(self.entry_value.get())

# Set the math button click so when equals is clicked
# that function knows what calculation to use
if value == "/":
print("/ Pressed")
self.div_trigger = True
elif value == "*":
print("* Pressed")
self.mult_trigger = True
elif value == "+":
print("+ Pressed")
self.add_trigger = True
else:
print("- Pressed")
self.sub_trigger = True

# Clear the entry box
self.number_entry.delete(0, "end")

# Performs a mathematical operation by taking the value before
# the math button is clicked and the current value. Then perform
# the right calculation by checking what math button was clicked
# last
def equal_button_press(self):

# Make sure a math button was clicked
if self.add_trigger or self.sub_trigger or self.mult_trigger or self.div_trigger:

if self.add_trigger:
solution = self.calc_value + float(self.entry_value.get())
elif self.sub_trigger:
solution = self.calc_value - float(self.entry_value.get())
elif self.mult_trigger:
solution = self.calc_value * float(self.entry_value.get())
else:
solution = self.calc_value / float(self.entry_value.get())


print(self.calc_value, " ", float(self.entry_value.get()),
" ", solution)

# Clear the entry box
self.number_entry.delete(0, "end")

self.number_entry.insert(0, solution)

def clear_button_press(self):
if True:
self.number_entry.delete(0, "end")


def __init__(self, root):
# Will hold the changing value stored in the entry
self.entry_value = StringVar(root, value="")

# Define title for the app
root.title("Calculator")

# Defines the width and height of the window
#root.geometry("581x236")

# Block resizing of Window
root.resizable(width=False, height=False)

# Customize the styling for the buttons and entry
style = ttk.Style()
style.configure("TButton",
font="Serif 16",
padding=10)

style.configure("TEntry",
font="Serif 50",
padding=20)

# Create the text entry box
self.number_entry = ttk.Entry(root,
textvariable=self.entry_value, width=77)
self.number_entry.grid(row=0, columnspan=7)


# 1st Row
self.buttondeg = ttk.Button(root, text="Deg", width="5", command=lambda: self.button_press('7')).grid(row=1, column=0)

self.buttonrad = ttk.Button(root, text="Rad", width="5", command=lambda: self.button_press('8')).grid(row=1, column=1)

self.buttonx = ttk.Button(root, text="x!", width="5", command=lambda: self.button_press('9')).grid(row=1, column=2)

self.buttonnail1 = ttk.Button(root, text="(", width="5", command=lambda: self.button_press('7')).grid(row=1, column=3)

self.buttonnail2 = ttk.Button(root, text=")", width="5", command=lambda: self.button_press('8')).grid(row=1, column=4)

self.buttonreminder = ttk.Button(root, text="%", width="5", command=lambda: self.button_press('9')).grid(row=1, column=5)

self.button_clear = ttk.Button(root, text="AC", width="5", command=lambda: self.clear_button_press()).grid(row=1, column=6)

# 2nd Row

self.buttoninv = ttk.Button(root, text="inv", width="5", command=lambda: self.button_press('7')).grid(row=2, column=0)

self.buttonsin = ttk.Button(root, text="sin", width="5", command=lambda: self.button_press('7')).grid(row=2, column=1)

self.buttonin = ttk.Button(root, text="in", width="5", command=lambda: self.button_press('7')).grid(row=2, column=2)

self.button7 = ttk.Button(root, text="7", width="5", command=lambda: self.button_press('7')).grid(row=2, column=3)

self.button8 = ttk.Button(root, text="8", width="5", command=lambda: self.button_press('8')).grid(row=2, column=4)

self.button9 = ttk.Button(root, text="9", width="5", command=lambda: self.button_press('9')).grid(row=2, column=5)

self.button_div = ttk.Button(root, text="÷", width="5", command=lambda: self.math_button_press('/')).grid(row=2, column=6)

# 3rd Row

self.buttonpi = ttk.Button(root, text="π", width="5", command=lambda: self.button_press("3.14")).grid(row=3, column=0)

self.buttoncos = ttk.Button(root, text="cos", width="5", command=lambda: self.button_press('4')).grid(row=3, column=1)

self.buttonlog = ttk.Button(root, text="log", width="5", command=lambda: self.button_press('4')).grid(row=3, column=2)

self.button4 = ttk.Button(root, text="4", width="5", command=lambda: self.button_press('4')).grid(row=3, column=3)

self.button5 = ttk.Button(root, text="5", width="5", command=lambda: self.button_press('5')).grid(row=3, column=4)

self.button6 = ttk.Button(root, text="6", width="5", command=lambda: self.button_press('6')).grid(row=3, column=5)

self.button_mult = ttk.Button(root, text="x", width="5", command=lambda: self.math_button_press('*')).grid(row=3, column=6)



self.buttone = ttk.Button(root, text="e", width="5", command=lambda: self.button_press('1')).grid(row=4, column=0)

self.buttontan = ttk.Button(root, text="tan", width="5", command=lambda: self.button_press('1')).grid(row=4, column=1)

self.buttonsqrt = ttk.Button(root, text="√", width="5", command=lambda: self.button_press("1")).grid(row=4, column=2)

self.button1 = ttk.Button(root, text="1", width="5", command=lambda: self.button_press('1')).grid(row=4, column=3)

self.button2 = ttk.Button(root, text="2", width="5", command=lambda: self.button_press('2')).grid(row=4, column=4)

self.button3 = ttk.Button(root, text="3", width="5", command=lambda: self.button_press('3')).grid(row=4, column=5)

self.button_sub = ttk.Button(root, text="-", width="5", command=lambda: self.math_button_press('-')).grid(row=4, column=6)


# 4th Row

self.buttonans = ttk.Button(root, text="Ans", width="5", command=lambda: self.button_press('0')).grid(row=5, column=0)

self.buttonexp = ttk.Button(root, text="EXP", width="5", command=lambda: self.button_press('0')).grid(row=5, column=1)

self.buttonpwr = ttk.Button(root, text="^", width="5", command=lambda: self.button_press('0')).grid(row=5, column=2)

self.button0 = ttk.Button(root, text="0", width="5", command=lambda: self.button_press('0')).grid(row=5, column=3)

self.buttondot = ttk.Button(root, text=".", width="5", command=lambda: self.button_press('.')).grid(row=5, column=4)

self.button_equal = ttk.Button(root, text="=", width="5", command=lambda: self.equal_button_press()).grid(row=5, column=5)

self.button_add = ttk.Button(root, text="+", width="5", command=lambda: self.math_button_press('+')).grid(row=5, column=6)


# Get the root window object
root = Tk()

# Create the calculator
calc = Calculator(root)

# Run the app until exited
root.mainloop()

Superior.Citizen
Автор

if you type alt+246 on the numpad in a Word document or something you get the real division symbol

matsbjnnes
Автор

Hi Derek,

Please, can you explain the function of the line below:

self.add_trigger = False
self.sub_trigger = False
self.mult_trigger = False
self.div_trigger = False

tom_greatpet
Автор

give us a setup tour !!!!, and q&a session - wat u do ?? hav a worked on any big projects ??

ovenky
Автор

great tutorial Derek. absolutely speechless

masoud
Автор

Please make a master series of web scrapping With python

MuhammadAhmad-bxrw
Автор

Hello Derek, I have got a question I hope you will see it and answer it ( that would be awesome). So recently I have been looking at C# tut's (that includes yours ! :D YAY !) But I don't really think I can manage it from a scratch. So my question is what would you recommend to start learning from ? My goal is to learn C++ but (others told me to learn different then start c++) so I want to know your opinion as I see you are experienced man so I might get some type of advice directly from you. So what would you recommend? Start with other language such as Python or head straight into the language that I want ? Thanks even for reading this ! P.S Have a wonderful day or night ( depends where you live). Once more thank you very much even if you don't answer it.

Katiffly
Автор

Please add "AC" button
first call a function and then call it in 4th row
then AC button will work

alwayssbijoy
Автор

Hey man can you make another project like this this was amazing i subbed 5 stars video

ThestarSTUNNNA
Автор

give us a setup tour, and q&a session - wat u do ??

ovenky
Автор

If anyone is looking for the code only then skip to 12:24

theweirdguy
Автор

another great video .. i am thinking of starting a movie review channel - is it better to do non-skippable ads or skippable? just looking for some advice from a major youtuber

wheel
Автор

Surely you could've just used the buttons to type a sum into a label, then get the label's text and use the eval() function to find the answer?

TeamViperUK
Автор

Thanks for an awesome tutorial once again. Could you possibly give a
hint as to how to implement the AC button to clear everything? Thanks!

yuvigerstein
Автор

great tutorial but how do I change the size and color of the buttons? If anyone would help me with this I would greatly appreciate it. I would prefer to know how to do it by entering a string as it would give me the ability to make random colors.

keithandrelashley
Автор

How would you change the code to keep what the user has entered in the entry widget? Also how would you include decimal points?

matthewlowe
visit shbcf.ru