Python calculator app 🖩
Vložit
- čas přidán 7. 09. 2024
- python calculator program project tutorial example explained
#python #calculator #program
****************************************************************
Python Calculator
****************************************************************
from tkinter import *
def button_press(num):
global equation_text
equation_text = equation_text + str(num)
equation_label.set(equation_text)
def equals():
global equation_text
try:
total = str(eval(equation_text))
equation_label.set(total)
equation_text = total
except SyntaxError:
equation_label.set("syntax error")
equation_text = ""
except ZeroDivisionError:
equation_label.set("arithmetic error")
equation_text = ""
def clear():
global equation_text
equation_label.set("")
equation_text = ""
window = Tk()
window.title("Calculator program")
window.geometry("500x500")
equation_text = ""
equation_label = StringVar()
label = Label(window, textvariable=equation_label, font=('consolas',20), bg="white", width=24, height=2)
label.pack()
frame = Frame(window)
frame.pack()
button1 = Button(frame, text=1, height=4, width=9, font=35,
command=lambda: button_press(1))
button1.grid(row=0, column=0)
button2 = Button(frame, text=2, height=4, width=9, font=35,
command=lambda: button_press(2))
button2.grid(row=0, column=1)
button3 = Button(frame, text=3, height=4, width=9, font=35,
command=lambda: button_press(3))
button3.grid(row=0, column=2)
button4 = Button(frame, text=4, height=4, width=9, font=35,
command=lambda: button_press(4))
button4.grid(row=1, column=0)
button5 = Button(frame, text=5, height=4, width=9, font=35,
command=lambda: button_press(5))
button5.grid(row=1, column=1)
button6 = Button(frame, text=6, height=4, width=9, font=35,
command=lambda: button_press(6))
button6.grid(row=1, column=2)
button7 = Button(frame, text=7, height=4, width=9, font=35,
command=lambda: button_press(7))
button7.grid(row=2, column=0)
button8 = Button(frame, text=8, height=4, width=9, font=35,
command=lambda: button_press(8))
button8.grid(row=2, column=1)
button9 = Button(frame, text=9, height=4, width=9, font=35,
command=lambda: button_press(9))
button9.grid(row=2, column=2)
button0 = Button(frame, text=0, height=4, width=9, font=35,
command=lambda: button_press(0))
button0.grid(row=3, column=0)
plus = Button(frame, text='+', height=4, width=9, font=35,
command=lambda: button_press('+'))
plus.grid(row=0, column=3)
minus = Button(frame, text='-', height=4, width=9, font=35,
command=lambda: button_press('-'))
minus.grid(row=1, column=3)
multiply = Button(frame, text='*', height=4, width=9, font=35,
command=lambda: button_press('*'))
multiply.grid(row=2, column=3)
divide = Button(frame, text='/', height=4, width=9, font=35,
command=lambda: button_press('/'))
divide.grid(row=3, column=3)
equal = Button(frame, text='=', height=4, width=9, font=35,
command=equals)
equal.grid(row=3, column=2)
decimal = Button(frame, text='.', height=4, width=9, font=35,
command=lambda: button_press('.'))
decimal.grid(row=3, column=1)
clear = Button(window, text='clear', height=4, width=12, font=35,
command=clear)
clear.pack()
window.mainloop()
****************************************************************
Bro Code merch store 👟 :
===========================================================
teespring.com/...
===========================================================
music credits 🎼 :
===========================================================
Up In My Jam (All Of A Sudden) by - Kubbi / kubbi
Creative Commons - Attribution-ShareAlike 3.0 Unported- CC BY-SA 3.0
Free Download / Stream: bit.ly/2JnDfCE
Music promoted by Audio Library • Up In My Jam (All Of A...
===========================================================
# ****************************************************************
# Python Calculator
# ****************************************************************
from tkinter import *
def button_press(num):
global equation_text
equation_text = equation_text + str(num)
equation_label.set(equation_text)
def equals():
global equation_text
try:
total = str(eval(equation_text))
equation_label.set(total)
equation_text = total
except SyntaxError:
equation_label.set("syntax error")
equation_text = ""
except ZeroDivisionError:
equation_label.set("arithmetic error")
equation_text = ""
def clear():
global equation_text
equation_label.set("")
equation_text = ""
window = Tk()
window.title("Calculator program")
window.geometry("500x500")
equation_text = ""
equation_label = StringVar()
label = Label(window, textvariable=equation_label, font=('consolas',20), bg="white", width=24, height=2)
label.pack()
frame = Frame(window)
frame.pack()
button1 = Button(frame, text=1, height=4, width=9, font=35,
command=lambda: button_press(1))
button1.grid(row=0, column=0)
button2 = Button(frame, text=2, height=4, width=9, font=35,
command=lambda: button_press(2))
button2.grid(row=0, column=1)
button3 = Button(frame, text=3, height=4, width=9, font=35,
command=lambda: button_press(3))
button3.grid(row=0, column=2)
button4 = Button(frame, text=4, height=4, width=9, font=35,
command=lambda: button_press(4))
button4.grid(row=1, column=0)
button5 = Button(frame, text=5, height=4, width=9, font=35,
command=lambda: button_press(5))
button5.grid(row=1, column=1)
button6 = Button(frame, text=6, height=4, width=9, font=35,
command=lambda: button_press(6))
button6.grid(row=1, column=2)
button7 = Button(frame, text=7, height=4, width=9, font=35,
command=lambda: button_press(7))
button7.grid(row=2, column=0)
button8 = Button(frame, text=8, height=4, width=9, font=35,
command=lambda: button_press(8))
button8.grid(row=2, column=1)
button9 = Button(frame, text=9, height=4, width=9, font=35,
command=lambda: button_press(9))
button9.grid(row=2, column=2)
button0 = Button(frame, text=0, height=4, width=9, font=35,
command=lambda: button_press(0))
button0.grid(row=3, column=0)
plus = Button(frame, text='+', height=4, width=9, font=35,
command=lambda: button_press('+'))
plus.grid(row=0, column=3)
minus = Button(frame, text='-', height=4, width=9, font=35,
command=lambda: button_press('-'))
minus.grid(row=1, column=3)
multiply = Button(frame, text='*', height=4, width=9, font=35,
command=lambda: button_press('*'))
multiply.grid(row=2, column=3)
divide = Button(frame, text='/', height=4, width=9, font=35,
command=lambda: button_press('/'))
divide.grid(row=3, column=3)
equal = Button(frame, text='=', height=4, width=9, font=35,
command=equals)
equal.grid(row=3, column=2)
decimal = Button(frame, text='.', height=4, width=9, font=35,
command=lambda: button_press('.'))
decimal.grid(row=3, column=1)
clear = Button(window, text='clear', height=4, width=12, font=35,
command=clear)
clear.pack()
window.mainloop()
Hi
Arigatou boss 。◕‿◕。
Heard of Github ?
0:25
At first I was like "Could you go a little more in-depth with explaining the code?" But. That's when I realized I need to go on my own for deeper explanations. It makes it so much easier and satisfying to get yourself unstuck. Great Lesson Bro!
Made a simple calculator :)
# Calculator program
# In python
#-----------------------------
def addition(x,y):
output1 = (x + y)
return output1
#-----------------------------
def subtraction(x,y):
output2 = (x - y)
return output2
#-----------------------------
def multiplication(x,y):
output3 = (x * y)
return output3
#-----------------------------
def division(x,y):
output = (x / y)
return output
#-----------------------------
def square(z):
output4 = (z * z)
return output4
#-----------------------------
def cube(z):
output5 = (z * z * z)
return output5
#-----------------------------
def factorial_pos(z):
output6 = 1
for i in range(z,1,-1):
output6 = (output6 * i)
return output6
#-----------------------------
def factorial_neg(z):
output7 = -1
for i in range(z,-1):
output7 = (output7 * i)
return output7
#-----------------------------
def exp_pos(b,p):
output8 = 1
for i in range(p):
output8 = (output8 * b)
return output8
#-----------------------------
def exp_neg(b,p):
output9 = -1
for i in range(p):
output9 = (output9 * b)
return output9
#-----------------------------
def mtp_tables_ps(x,y):
print("
Result:
")
for i in range(1,y+1):
print(f"{x} x {i} = {x*i}")
else:
print(f'''
These are the multiplication tables
of {x} with-in the range of {y}''')
#-----------------------------
def mtp_tables_ng(x,y):
print("
Result:
")
for i in range(-1,(y-1),-1):
print(f"{x} x {i} = {x*i}")
else:
print(f'''
These are the multiplication tables
of {x} with-in the range of {y}''')
#-----------------------------
def operator(c):
if(c == ('+')):
try:
x = float(input("Enter 1st number
: "))
y = float(input("Enter 2nd number
: "))
except ValueError:
print("You can only enter integers.Try to run again!")
else:
print("Result:")
print(addition(x,y))
elif(c == ('-')):
try:
x = float(input("Enter 1st number
: "))
y = float(input("Enter 2nd number
: "))
except ValueError:
print("You can only enter integers.Try to run again!")
else:
print("Result:")
print(subtraction(x,y))
elif(c == ('*')):
try:
x = float(input("Enter 1st number
: "))
y = float(input("Enter 2nd number
: "))
except ValueError:
print("You can only enter integers.Try to run again!")
else:
print("Result:")
print(multiplication(x,y))
elif(c == ('/')):
try:
x = float(input("Enter 1st number
: "))
y = float(input("Enter 2nd number
: "))
division(x,y)
except ValueError:
print("You can only enter integers.Try to run again!")
except ZeroDivisionError:
print("You cant divide by 0.Try to run again!")
else:
print("Result:")
print(division(x,y))
elif(c == ("**")):
try:
z = float(input("Enter the number to sqaure it
: "))
except ValueError:
print("You can only enter integers.Try to run again!")
else:
print("Result:")
print(square(z))
elif(c == ("***")):
try:
z = float(input("Enter the number to cube it
: "))
except ValueError:
print("You can only enter integers.Try to run again!")
else:
print("Result:")
print(cube(z))
elif(c == ('!')):
try:
z = int(input("Enter the number to calculate its factorial
: "))
if(z > 0):
print("Result:")
print(factorial_pos(z))
elif(z < 0):
print("Result:")
print(factorial_neg(z))
else:
if(z == 0):
print("Result:")
print(z*0)
else:
pass
except ValueError:
print("You can only enter Integers.Try to run again!")
elif(c == ('exp')):
try:
b = int(input("Enter the base number
: "))
p = int(input("Enter the power number
: "))
if(p < 0):
print("You cant enter negative integers as Power.Try to run again!")
elif(b > 0):
print("Result:")
print(exp_pos(b,p))
elif(b < 0):
print("Result:")
print(exp_neg(b,p))
elif(b == 0):
print("Result:")
print(b*0)
else:
pass
except ValueError:
print("You can only enter Integers.Try to run again!")
elif(c == "mtp"):
try:
x = int(input("Enter the number for its multiplication tables
: "))
y = int(input("Enter the range for the tables
: "))
if(y > 0):
mtp_tables_ps(x,y)
elif(y < 0):
mtp_tables_ng(x,y)
else:
print("Result:")
print(x*y)
except ValueError:
print("You can only enter Integers.Try to run again!")
else:
print("Invalid operator!")
#-----------------------------
def new_program(c):
c = input('''Enter an operator sign:
('+' , '-' , '*' , '/' , '**' , '***' , '!' , 'exp' , 'mtp')
: ''')
operator(c)
#-----------------------------
c = input('''Enter an operator sign:
('+' , '-' , '*' , '/' , '**' , '***' , '!' , 'exp' , 'mtp')
: ''')
operator(c)
print()
ctn = input('''Do you want to continue your calculation?
Enter 'y' for Yes / 'n' for No.
: ''')
ctn_cmd = ['y','Y','n','N']
while(ctn == 'y' or ctn == 'Y'):
print()
new_program(c)
print()
ctn = input('''Do you want to continue your calculation?
Enter 'y' for Yes / 'n' for No.
: ''')
if(ctn == 'n' or ctn == 'N'):
print()
print("Thank you for using the calculator.
")
else:
if(ctn not in ctn_cmd):
print("Invalid command!Try to run again.")
else:
pass
#-----------------------------
# Code finished successfully
awesome!!! but little bit hard to read
Imagine watching your tortural I can't remember very well I like isolated myself not knowing once again I can see such beautiful python lesson may God bless wherever you are ❤❤
This is an awesome tutorial bro! Keep it up.
As a python learner I want to know how can I bind keyboard keys in this calculator.
thank you so much.. i had so much fun creating this project.
liked and subscribed
your try is good thanks
From deep of my heart. Thanks very much!!!
i really love the way that you tech bro i am grateful to be taught by u thank you
realy thanks bro yu are aprofessional and this lesson is very useful thanks again ♥♥
My buttons are not working even though I checked the video a lot of times and they won’t do anything when pressed. Do you know how to fix this?
Same here
same
wow this is very helpful
I really love your channel
thanks this tutorial was really helpfull
commented and subscribed
Here is the short cut for creating buttons through 9 to 1, order is 9 to 1 not like in Bro's code as 1 to 9, however you can change order if you want;
btns = []
btns_nmbr = -1
for x in range(0, 3):
for y in range(0, 3):
btns_nmbr += 1
btns.append(Button(frame, text=9 - btns_nmbr, height=4, width=9, font=35,
command=lambda btns_nmbr=btns_nmbr: button_press(9 - btns_nmbr)))
btns[btns_nmbr].grid(row=x, column=y)
for other buttons , i think we still need to define it seperately.
step 3 = done
step 1 = done 👍
step 2 = done 🗯
great work again Bro!
This video is helpful
thanks for the short and understandable tutorial
Great video!
I am not gonna lie it is criminal to be this good at code
Love the channel !
thnx for the tutorial
I tried to code it myself before this, it went well but I made each function for each number, i probably need to learn more lol
Thanks so much. I love this video
Thankk you bro codee this is a good tkinter study
Thank you from Spain
Thank you so much...it really helps me❤️
Amazing content Bro ❤
Hi bro, I'm a beginner in Python.
First of all, thank you for the video, it helped me a lot.
Second, I have a question: (I apologize if I make any grammatical mistakes, as I'm not very good at writing English)
Why did you use lambda functions for the buttons? When I remove the lambda functions from the buttons and run the program, all the numbers and symbols are displayed without pressing any buttons. What is the reason for this?
Thanks. equation_label = StringVar() is not trivial - I had to look up more info. Is it automatically global, and in scope in all of the defined functions?
Hi Bro, Quick question about the use of the lambda expression - How are you able to write the lambda expression for the command option this way. The way lambda is used seems to be a departure from how the format for a lambda expression is. Thanks.
thank you sosososososoososososooooooooooooooooo much ❤
Nice
cool
excelent bro..
How do I change the size of the font without removing the perfect square of the button and make it fit and change the button to border radius having a circle border please help
This really helped me, thanks bro
tnx
❤❤❤❤
noice vids dude!
Thanks a lot BRO
YOUR A LIFE SAVER
Thank you so much bro!
mewo (just to doing what u said at the finish)
amazing
hi Bro and all here, the equal function is not working, is it mine alone...
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Shahzad\PycharmProjectsFIRSTFROG\pythonProject3\almas6.py", line 78, in
except "Syntax Error":
TypeError: catching classes that do not inherit from BaseException is not allowed
Process finished with exit code 1
my program have no error...but still output is this.....what can i do
i love you bro
can someone please tell how to add operators like log, sin, cos, tan from math library in this?
import math and make seperate functions with a matrix of quasi polar tensors summating at the origin of the orthogonal riemman sums
My buttons on calculator don't work, do you now how to fix it?
How would you fix the decimal + decimal issue where it gives you a run on number?
very good
i have power "to 2k to 2.1k" but i will give a prayer to yt algo
Bro Code, i wanna ask you, maybe it's stupid question, sorry for that. We have class and examples of class - objects. Question: how to make some visible object with its own properties and methods? For example i'd like to know how to create a text frame, wich i could paint on a form, i mean it's like in programm Photoshop or Adobe InDesign.
In the video that he made the several balls animation he did something similar only that he created them as labels like oval widgets but can also be done in a different way by creating potoimage variables, and then passing them as arguments after self. it's actually easier since you will need less parameters. For example you won't need to pass fill color.
I would like to thank you for your fantastic tutorials, they are helpful,
and I have a question how can use both keyboard and button to enter numbers in calculator program.
so late but I think you should watch the keyboard events lesson on his channel.
you will use the window.bind method I think
@@abdallahbadr4335 I'm using window.bind function to call button_press(), but button_press function is getting executed automatically when running a code. please help.
window.bind("", button_press("+"))
love u king
thanks
thanks so much
Hi Bro Code, what would i do if i wanted to created an extra button called 'pi' and make it when i press it, it solve pi so show me in the box 3.14... ??? how would i do that
Either you can import math and check the available syntax in internet documentation or you create a function containing the operation which will result in the value of pi. for example check some circle that has been measured an take those numbers length of circle devided by it's diameter, and you probably want to make it a float number as well to show all decimals using float()
or float.
@@davidcalebpaterson7101 hey i wanted to use the log operator but i am not able to do so? can you tell me the code or guide me through it? thanks
Thank you Bro!
Hi ,bro thank you for this video....I'm using pydroid3. I have followed all the steps but is saying line 40, in ,equation_label = stringVar()
NameError : name StringVar is not defined....
Help bro...and everyone
i don't understand why we need to put the button commands as lambda functions. aren't they already functions? why can't we just type "command=button_press()". what does lambda change in this case?
the lambda function is actually quite important for the making of the whole thing.
usually when we make a button its for example:
button1 = Button1(window, command = button_press)
however, in this case we have to pass in an argument for the button_press() function, with num as its parameter (button_press(num))
by doing button1=Button1(window,command = button_press(1)), we call the function since we added parenthesis at the back of the function, before the button is even pressed. Of course we dont want the command / function bounded to a button to execute before we even press a button, but we cant pass an argument without parathesis (brackets) either, so this is where lambda comes in.
The lambda function will prevent the command bounded to the button to activate before we press the button by creating a function on the spot with the expression button_press(1). Hope this helps.
@@onlyLewds
An anonymous function ୧| ͡ᵔ ﹏ ͡ᵔ |୨
And me as a beginner i can't undastand anything
I thought it would take over 300 to 500 lines of code, and then suddenly only 125
Pls help me!!!
I don't know how to install tkinter at cmd.
I write "pip install tkinter" but the pc gives me this error:
ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none)
ERROR: No matching distribution found for tkinter
How can I solve this problem??
you don`t need cmd, you can install any package from pycharm itself. go to file(In the upper corner of the program), then press at sittings button, after that press (pythonProject), then choose Python Interpreter, you will find a little plus sign, press at it, write tkinter and install it. (you can use this method to install any kind of packages on pycharm).. i hope i could help you.
good
anyone knows how to add additional feature where you can use your keyboard to use this calculator?
So I just got here on my journey with Bro and python and maybe its not the most optimal solution but it works, I also added backspace for the keyboard, hope it helps :D
from tkinter import *
keylist = ["1","2","3","4","5","6","7","8","9","0","-","+","*","/","."]
def button_press(num):
global equation_text
equation_text = equation_text + str(num)
equation_label.set(equation_text)
def backspace():
global equation_text
equation_text = equation_text[:-1]
equation_label.set(equation_text)
def button_press_keyboard(event):
# print(event.char)
# print(event.keysym)
global equation_text
if event.char in keylist:
equation_text = equation_text + event.char
equation_label.set(equation_text)
elif event.keysym == "Return":
equals()
elif event.keysym == "BackSpace":
backspace()
elif event.keysym == "c":
clear()
else:
pass
def equals():
global equation_text
try:
total = str(eval(equation_text))
equation_label.set(total)
equation_text = total
except SyntaxError:
equation_label.set("syntax error")
equation_text=""
except ZeroDivisionError:
equation_label.set("arithmetic error")
equation_text=""
def clear():
global equation_text
equation_label.set("")
equation_text = ""
window = Tk()
window.title("Calculator")
window.geometry("500x500")
window.bind("",button_press_keyboard)
equation_text = ""
equation_label = StringVar()
label = Label(window, textvariable=equation_label, font=('consolas',20), bg="white", width="24", height="2")
label.pack()
frame = Frame(window)
frame.pack()
button1 = Button(frame, text=1, height=4, width=9, font=35,
command= lambda: button_press(1))
button1.grid(row=0,column=0)
button2 = Button(frame, text=2, height=4, width=9, font=35,
command= lambda: button_press(2))
button2.grid(row=0,column=1)
button3 = Button(frame, text=3, height=4, width=9, font=35,
command= lambda: button_press(3))
button3.grid(row=0,column=2)
button4 = Button(frame, text=4, height=4, width=9, font=35,
command= lambda: button_press(4))
button4.grid(row=1,column=0)
button5 = Button(frame, text=5, height=4, width=9, font=35,
command= lambda: button_press(5))
button5.grid(row=1,column=1)
button6 = Button(frame, text=6, height=4, width=9, font=35,
command= lambda: button_press(6))
button6.grid(row=1,column=2)
button7 = Button(frame, text=7, height=4, width=9, font=35,
command= lambda: button_press(7))
button7.grid(row=2,column=0)
button8 = Button(frame, text=8, height=4, width=9, font=35,
command= lambda: button_press(8))
button8.grid(row=2,column=1)
button9 = Button(frame, text=9, height=4, width=9, font=35,
command= lambda: button_press(9))
button9.grid(row=2,column=2)
button0 = Button(frame, text=0, height=4, width=9, font=35,
command= lambda: button_press(0))
button0.grid(row=3,column=0)
plus = Button(frame, text='+', height=4, width=9, font=35,
command= lambda: button_press('+'))
plus.grid(row=0,column=3)
minus = Button(frame, text='-', height=4, width=9, font=35,
command= lambda: button_press('-'))
minus.grid(row=1,column=3)
multiply = Button(frame, text='*', height=4, width=9, font=35,
command= lambda: button_press('*'))
multiply.grid(row=2,column=3)
divide = Button(frame, text='/', height=4, width=9, font=35,
command= lambda: button_press('/'))
divide.grid(row=3,column=3)
equal = Button(frame, text='=', height=4, width=9, font=35,
command=equals)
equal.grid(row=3,column=2)
decimal = Button(frame, text='.', height=4, width=9, font=35,
command=lambda: button_press('.'))
decimal.grid(row=3,column=1)
clearbtn = Button(window, text='Clear', height=4, width=20, font=35,
command=clear)
clearbtn.pack()
window.mainloop()
he is on fire mode
Hi Bro Code. is there a way for me to create a pytest with this kind of code?
AttributeError: 'str' object has no attribute 'tk' i am getting this error when i press any buttons and i am not sure why
OMG. Thanks❤❤❤
Your the best dude🗿
thx bro
Here, in def equals the equation text is an empty string then how it can evaluate.. Anyone please explain
More JavaFX Videos Please
I understand, but I don't want my Python people to feel left out
Bien
I was adding some more operators to the code and I accidentally broke the clear button ._.
thank u man
Can someone explain to me what the stringvar and lambda does?
stringvar is function which hold the value of the ouput and chages it to current value and lamba is function and it is concise way of writing long code into short code
I only have 1 problem, whenever I am pressing the buttons the text is not showing. I am currently using pycharm on my mac. Is there a reason for this?
same situation bro... i don't know why
I figured it out, I compared the code and for me it was on the
label = tk.Label(window, textvariable=equation_text
line. the text part should be label.
what compiler is this?
Bro
can someone plz tell me why he used lambda function I still don't get it ?
I get your confusion. It *looks* as if writing "command=somefunction()" will do what you want, but don't be misled; when you run your program, Python will actually call somefunction() immediately AS PART OF SETTING UP YOUR BUTTON. This is not what you want. Instead, using a lambda expression here tells simply Python to run somefunction() ONLY if and when the button is clicked.
Why there is no clear button
And how can this code be used on a pytest?I need answers too
Iran left the chat
comment
comment dropped
THANK YOU @BroCodez 😘
C:\Users\gilca\PycharmProjects\pythonProject1\intro\Scripts\python.exe C:\Users\gilca\PycharmProjects\pythonProject1\main.py
File "C:\Users\gilca\PycharmProjects\pythonProject1\main.py", line 15
Label = Label(window,textvariable=equation_label, font=('consolas', 20),
^
SyntaxError: '(' was never closed
Process finished with exit code 1
I have this error even if I use the original code from the video description . I tried many times and I don t understand what s the problem.
I also use : except SyntaxError:
equation_label.set("syntax error")
equation_text = ""
comment