Python calculator app 🖩

Поделиться
HTML-код
  • Опубликовано: 31 янв 2021
  • 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/stores/bro-code-5
    ===========================================================
    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...
    ===========================================================
  • НаукаНаука

Комментарии • 112

  • @BroCodez
    @BroCodez  3 года назад +79

    # ****************************************************************
    # 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()

  • @blazer125
    @blazer125 2 года назад +42

    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!

  • @juankorsia7909
    @juankorsia7909 2 года назад +2

    From deep of my heart. Thanks very much!!!

  • @mrbrain8385
    @mrbrain8385 3 года назад +2

    I really love your channel

  • @damdom2007
    @damdom2007 Год назад +2

    thank you so much.. i had so much fun creating this project.
    liked and subscribed

  • @user-sj2mj5qw3o
    @user-sj2mj5qw3o 11 месяцев назад

    thanks for the short and understandable tutorial

  • @baahubaliankit5596
    @baahubaliankit5596 2 года назад +2

    i really love the way that you tech bro i am grateful to be taught by u thank you

  • @2ncielkrommalzeme210
    @2ncielkrommalzeme210 Год назад +2

    your try is good thanks

  • @sebastiandworczyk4618
    @sebastiandworczyk4618 Год назад +1

    Love the channel !

  • @tread2114
    @tread2114 Год назад +1

    Great video!

  • @jamil_faruk
    @jamil_faruk 2 года назад +11

    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.

  • @theaddictor
    @theaddictor 3 года назад +2

    Thank you so much...it really helps me❤️

  • @adityanaik099
    @adityanaik099 2 года назад +29

    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

  • @im_a-walking_shitpost_machine
    @im_a-walking_shitpost_machine Год назад +1

    wow this is very helpful

  • @jaumemoreno2544
    @jaumemoreno2544 2 года назад +1

    Thank you from Spain

  • @user-og3qh7xl8t
    @user-og3qh7xl8t 10 месяцев назад

    Thanks so much. I love this video

  • @kapibara2440
    @kapibara2440 7 месяцев назад

    Amazing content Bro ❤

  • @tmahad5447
    @tmahad5447 2 года назад +1

    This video is helpful

  • @harshbhadrawale2645
    @harshbhadrawale2645 2 месяца назад

    thanks this tutorial was really helpfull

  • @hamzaammar4356
    @hamzaammar4356 3 года назад +1

    YOUR A LIFE SAVER

  • @akazagiyu
    @akazagiyu 11 месяцев назад

    Thankk you bro codee this is a good tkinter study

  • @mustefaosman2893
    @mustefaosman2893 7 месяцев назад +1

    This really helped me, thanks bro

  • @user-vw6rl2dy2r
    @user-vw6rl2dy2r Месяц назад

    realy thanks bro yu are aprofessional and this lesson is very useful thanks again ♥♥

  • @soulninjadev
    @soulninjadev 3 года назад +1

    noice vids dude!

  • @shahzodsayfiddinov9510
    @shahzodsayfiddinov9510 3 года назад +2

    Thank you Bro!

  • @oguzhantopaloglu9442
    @oguzhantopaloglu9442 3 года назад +2

    amazing

  • @blexbottt5119
    @blexbottt5119 Год назад +2

    Thank you so much bro!

  • @prabhathprabhath9177
    @prabhathprabhath9177 5 месяцев назад

    excelent bro..

  • @jhassee
    @jhassee Год назад +1

    commented and subscribed

  • @omarsucess
    @omarsucess 10 месяцев назад +1

    thanks so much

  • @THEMINECRAFTWARDEN4279
    @THEMINECRAFTWARDEN4279 Год назад +1

    OMG. Thanks❤❤❤

  • @angelahamidi4274
    @angelahamidi4274 3 года назад +2

    i love you bro

  • @NOTHING-en2ue
    @NOTHING-en2ue Год назад +1

    thank you sosososososoososososooooooooooooooooo much ❤

  • @user-nt6gm5ge4t
    @user-nt6gm5ge4t 2 года назад +2

    love u king

  • @souravsarkar6107
    @souravsarkar6107 2 года назад +2

    thanks

  • @chikamalik3260
    @chikamalik3260 Месяц назад

    Thanks a lot BRO

  • @Skelton24
    @Skelton24 Год назад +1

    Your the best dude🗿

  • @coachbussimulator6831
    @coachbussimulator6831 2 года назад +3

    cool

  • @arshiaa104
    @arshiaa104 Год назад +1

    tnx
    ❤❤❤❤

  • @IMCYT
    @IMCYT 2 года назад +1

    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

  • @oukirimiryad9585
    @oukirimiryad9585 7 месяцев назад

    thx bro

  • @bahaaahmed7056
    @bahaaahmed7056 11 месяцев назад +1

    thank u man

  • @user-qh5kb7rv7o
    @user-qh5kb7rv7o 22 дня назад

    very good

  • @dollykahar7837
    @dollykahar7837 Год назад +1

    Nice

  • @milky_edge1123
    @milky_edge1123 Год назад

    I am not gonna lie it is criminal to be this good at code

  • @adamritchey3327
    @adamritchey3327 Год назад +1

    How would you fix the decimal + decimal issue where it gives you a run on number?

  • @w.p.c.7113
    @w.p.c.7113 2 года назад +1

    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.

    • @abdallahbadr4335
      @abdallahbadr4335 Год назад +2

      so late but I think you should watch the keyboard events lesson on his channel.
      you will use the window.bind method I think

    • @udayvadecha2973
      @udayvadecha2973 7 месяцев назад

      @@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("+"))

  • @EmanQalqon
    @EmanQalqon 3 месяца назад

    good

  • @rajeevkumarjha8748
    @rajeevkumarjha8748 2 месяца назад

    he is on fire mode

  • @abo.noran.
    @abo.noran. Год назад +1

    mewo (just to doing what u said at the finish)

  • @BigMarc-wn1kw
    @BigMarc-wn1kw 2 года назад +6

    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?

  • @davidhirschhorn2960
    @davidhirschhorn2960 3 месяца назад

    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?

  • @rishisid
    @rishisid 3 года назад +1

    More JavaFX Videos Please

    • @BroCodez
      @BroCodez  3 года назад +11

      I understand, but I don't want my Python people to feel left out

  • @caseywong8565
    @caseywong8565 6 дней назад

    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.

  • @idevsl8245
    @idevsl8245 3 года назад +2

    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.

    • @davidcalebpaterson7101
      @davidcalebpaterson7101 2 года назад +4

      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.

  • @aveeopppp1428
    @aveeopppp1428 4 месяца назад +1

    i have power "to 2k to 2.1k" but i will give a prayer to yt algo

  • @code.678
    @code.678 Год назад +2

    My buttons on calculator don't work, do you now how to fix it?

  • @ComparisonEditzMC
    @ComparisonEditzMC Месяц назад

    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

  • @fwblitzz
    @fwblitzz 11 месяцев назад

    what compiler is this?

  • @danielkamau8436
    @danielkamau8436 2 года назад +2

    hi Bro and all here, the equal function is not working, is it mine alone...

  • @MiguelArturoAsteteMedran-oi9xw
    @MiguelArturoAsteteMedran-oi9xw 9 месяцев назад

    Bien

  • @guljain1684
    @guljain1684 Год назад +4

    can someone please tell how to add operators like log, sin, cos, tan from math library in this?

    • @coopahtroopah69
      @coopahtroopah69 8 месяцев назад

      import math and make seperate functions with a matrix of quasi polar tensors summating at the origin of the orthogonal riemman sums

  • @Joseph20003
    @Joseph20003 4 месяца назад

    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?

  • @atoprak00
    @atoprak00 2 года назад +8

    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.

  • @zekzyarts
    @zekzyarts 3 года назад +2

    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

    • @davidcalebpaterson7101
      @davidcalebpaterson7101 2 года назад +1

      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.

    • @guljain1684
      @guljain1684 Год назад

      @@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

  • @DestinyNiesi
    @DestinyNiesi 2 месяца назад

    Hi Bro Code. is there a way for me to create a pytest with this kind of code?

  • @_Tomaszeq
    @_Tomaszeq 2 года назад +1

    I thought it would take over 300 to 500 lines of code, and then suddenly only 125

  • @THEGHOST-gl4ud
    @THEGHOST-gl4ud Год назад +1

    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

  • @ba.youtube1007
    @ba.youtube1007 2 года назад +2

    anyone knows how to add additional feature where you can use your keyboard to use this calculator?

    • @kubaw3861
      @kubaw3861 2 года назад

      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()

  • @Studios9796
    @Studios9796 7 месяцев назад

    Bro

  • @user-ds9lw9xx5g
    @user-ds9lw9xx5g 6 месяцев назад

    AttributeError: 'str' object has no attribute 'tk' i am getting this error when i press any buttons and i am not sure why

  • @ChintaAkhil-hj8up
    @ChintaAkhil-hj8up 9 месяцев назад

    Here, in def equals the equation text is an empty string then how it can evaluate.. Anyone please explain

  • @locrilydian
    @locrilydian 2 года назад +6

    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?

    • @onlyLewds
      @onlyLewds 2 года назад +9

      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.

    • @numerousoriabure459
      @numerousoriabure459 Год назад

      @@onlyLewds
      An anonymous function ୧⁠|⁠ ͡⁠ᵔ⁠ ⁠﹏⁠ ͡⁠ᵔ⁠ ⁠|⁠୨

    • @abhi-bs6280
      @abhi-bs6280 Год назад

      And me as a beginner i can't undastand anything

  • @almasshehzadi
    @almasshehzadi 6 месяцев назад

    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

  • @nicolatosatti6628
    @nicolatosatti6628 2 года назад +1

    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??

    • @ranabarham3452
      @ranabarham3452 2 года назад +1

      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.

  • @cattooo7273
    @cattooo7273 Год назад

    comment dropped

  • @the_aimless_most
    @the_aimless_most 4 дня назад

    I was adding some more operators to the code and I accidentally broke the clear button ._.

  • @amenkalai8442
    @amenkalai8442 11 месяцев назад

    can someone plz tell me why he used lambda function I still don't get it ?

    • @clivegreen7139
      @clivegreen7139 10 месяцев назад

      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.

  • @Victory-py7lp
    @Victory-py7lp 5 месяцев назад

    Can someone explain to me what the stringvar and lambda does?

    • @withmrbox
      @withmrbox 10 дней назад

      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

  • @Eagleman9191
    @Eagleman9191 8 месяцев назад

    Iran left the chat

  • @clashoflegends7035
    @clashoflegends7035 2 месяца назад

    Why there is no clear button

    • @DestinyNiesi
      @DestinyNiesi 2 месяца назад

      And how can this code be used on a pytest?I need answers too

  • @vtWub
    @vtWub Год назад +1

    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?

    • @jaspreetsingh7441
      @jaspreetsingh7441 Год назад

      same situation bro... i don't know why

    • @fwblitzz
      @fwblitzz 11 месяцев назад

      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.

  • @arpanshah355
    @arpanshah355 Год назад

    comment

  • @derpfisti2457
    @derpfisti2457 Год назад +1

    step 3 = done
    step 1 = done 👍
    step 2 = done 🗯
    great work again Bro!

  • @coriesalen6966
    @coriesalen6966 9 месяцев назад

    THANK YOU @BroCodez 😘

  • @Xynex11
    @Xynex11 7 месяцев назад

  • @g.g.9524
    @g.g.9524 22 дня назад

    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 = ""

  • @arpanshah355
    @arpanshah355 Год назад

    comment