-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.py
112 lines (87 loc) · 2.82 KB
/
calculator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from tkinter import *
import math
#define the colors
floral_white="#FEF9EF"
light_blue = "#A2D2FF"
label_color = "#000000"
#define the font
font=("Arial", 30)
#the variable expression will contain the arithmetic expression to calculate
expression=""
#1-the fonction press that will be used when we press on a button
def press(button):
# if the user will press the button "=", we display the result of the expression
if button=="=":
calculate()
return
#if the user will press the button "C" to delete, the content of the display screen is deleted
elif button=="C":
#for this we call the function delete
delete()
return
#otherwise if the user will press any another button, it will be included in the expression
global expression
#the case of x²
if button=="x²":
expression+='²'
#the case of √x
elif button=="√x":
expression+='√'
#the case of any other button
else:
expression+=str(button)
#display the expression
equation.set(expression)
#2-the function calculate which allows to calculate the result of the expression
def calculate():
#
global expression
try:
#eval function evaluate the expression
total=str(eval(expression))
#update the equation by using set method
equation.set(total)
expression=total
#if error is generate then handle by the except block
except:
equation.set("erreur")
expression=""
#3-the function delete which allows you to delete the content of the display screen
def delete():
#point out the global expression variable
global expression
expression=""
equation.set("")
#the design part of the calculator's graphical interface
if __name__ == "__main__":
gui = Tk()
#background color
gui.configure(background=floral_white)
#the title of the application
gui.title("calculator")
#window size
gui.geometry("190x350")
#variables pour stocker le contenu
equation=StringVar()
#result box
result = Label(gui, bg=floral_white, fg=label_color, textvariable=equation, height=2)
result.grid(columnspan=4)
#define buttons
buttons=['C','x²','√x','/',7,8,9,'*',4,5,6,'-',1,2,3,'+',0,'.']
#add buttons
row=1
column=0
for button in buttons:
b = Label(gui, text=str(button), bg=light_blue, fg=label_color, height=4, width=6)
b.bind("<Button-1>", lambda e,bouton=button: press(bouton))
b.grid(row=row,column= column)
column+=1
if column==4:
column=0
row+=1
#add the button =
b = Label(gui, text="=", bg=floral_white, fg=label_color, height=4, width=12)
b.bind("<Button-1>", lambda e: calculate())
b.grid(row=5, column=2, columnspan=2)
#start the GUI
gui.mainloop()