Amazing-Python-Scripts

Форк
0
281 строка · 7.1 Кб
1
################################################### Scientific Calculator ###################################################
2
################################################## Made By Avdhesh Varshney #################################################
3
############################################ (https://github.com/Avdhesh-Varshney) ##########################################
4

5
# Importing Modules
6
from tkinter import *
7
import tkinter.messagebox as tmsg
8
import math as m
9

10
# Initialising Tkinter module
11
root = Tk()
12

13
# Fixing the size of the calculator screen
14
root.minsize(520, 340)
15
root.maxsize(520, 340)
16

17
# Title of the calculator
18
root.title("Scientific Calculator")
19
root.wm_iconbitmap("calculator.ico")
20

21
sc = StringVar()
22
sc = Entry(root, width=31, textvariable=sc,
23
           relief=SUNKEN, font="cosmicsansms 20")
24
sc.grid(row=0, column=0, columnspan=10, padx=11, pady=12)
25

26
# Helping messages
27

28

29
def helper():
30
    help = '''1. For the following functions please enter the number first and then press the required function:
31
sin, cos, tan, log, ln, √, !, rad, degree, 1/x, π, e 
32

33
2. For multiplication with float numbers, say 5*0.4 multiply like 5*4/10'''
34
    # Adding message into the menu bar of the calculator
35
    tmsg.showinfo("Help", help)
36

37

38
# About section of the header
39
def abt():
40
    abt_text = "This calculator was developed using Tkinter, by Avdhesh Varshney.\n\n"
41
    abt_text += "A student of Dr. B R Ambedkar National Institute of Technology, Jalandhar.\n\n"
42
    abt_text += "Click the link below to access the GitHub account:\n\n"
43
    abt_text += "https://github.com/Avdhesh-Varshney"
44

45
    # Appending the link to the message in the about section of the menu bar
46
    tmsg.showinfo("About", abt_text)
47

48

49
# Suggestion to the user of the scientific calculator
50
def const():
51
    msg = '''If you press constants like:  π and e, 2 times, the result will be square of that constant. 
52
That means number of times you press the constant, the result will be constant to the power that number. '''
53
    tmsg.showinfo("Help", msg)
54

55

56
# Initialising main screen/root of the calculator
57
mainmenu = Menu(root)
58

59
# Adding menu bar in the calculator
60
submenu = Menu(mainmenu, tearoff=0)
61
submenu.add_command(label="General", command=helper)
62
submenu.add_command(label="Constants", command=const)
63
mainmenu.add_cascade(label="Help", menu=submenu)
64

65
# Append the author details
66
mainmenu.add_command(label="About", command=abt)
67

68
# Append the exit button
69
mainmenu.add_command(label="Exit", command=quit)
70

71
# Finally set the configuration in the screen of the calculator made by Tkinter library
72
root.config(menu=mainmenu)
73

74

75
# Creating a function which helps to calculate the different function in scientific calculator
76
def scientificCalc(event):
77
    # After event is triggered, performing different operation according to the command of the user
78
    key = event.widget
79
    text = key['text']
80
    val = sc.get()
81
    sc.delete(0, END)
82

83
    # Checking the function i.e., which function is triggered by the user
84

85
    # Trigonometric functions
86
    if text == "sin":
87
        sc.insert(0, m.sin(float(val)))
88

89
    elif text == "cos":
90
        sc.insert(0, m.cos(float(val)))
91

92
    elif text == "tan":
93
        sc.insert(0, m.tan(float(val)))
94

95
    # Logarithmic functions
96
    elif text == "log":
97
        if (float(val) <= 0.00):
98
            sc.insert(0, "Not Possible")
99
        else:
100
            sc.insert(0, m.log10(float(val)))
101

102
    elif text == "ln":
103
        if (float(val) <= 0.00):
104
            sc.insert(0, "Not Possible")
105
        else:
106
            sc.insert(0, m.log(float(val)))
107

108
    # Exponential functions
109
    elif text == "√":
110
        sc.insert(0, m.sqrt(float(val)))
111

112
    elif text == "!":
113
        sc.insert(0, m.factorial(int(val)))
114

115
    # Angular functions
116
    elif text == "rad":
117
        sc.insert(0, m.radians(float(val)))
118

119
    elif text == "deg":
120
        sc.insert(0, m.degrees(float(val)))
121

122
    # Constants functions
123
    elif text == "π":
124
        if val == "":
125
            ans = str(m.pi)
126
            sc.insert(0, ans)
127
        else:
128
            ans = str(float(val) * (m.pi))
129
            sc.insert(0, ans)
130

131
    elif text == "1/x":
132
        if (val == "0"):
133
            sc.insert(0, "ꝏ")
134
        else:
135
            sc.insert(0, 1/float(val))
136

137
    elif text == "e":
138
        if val == "":
139
            sc.insert(0, str(m.e))
140
        else:
141
            sc.insert(0, str(float(val) * (m.e)))
142

143

144
# Function to check click events
145
def click(event):
146
    key = event.widget
147
    text = key['text']
148
    oldValue = sc.get()
149
    sc.delete(0, END)
150
    newValue = oldValue + text
151
    sc.insert(0, newValue)
152

153

154
# Clear the calculator screen
155
def clr(event):
156
    sc.delete(0, END)
157

158

159
# Delete the entered text or number one by one
160
def backspace(event):
161
    entered = sc.get()
162
    length = len(entered) - 1
163
    sc.delete(length, END)
164

165

166
# Calculate function is triggered
167
def calculate(event):
168
    answer = sc.get()
169
    if "^" in answer:
170
        answer = answer.replace("^", "**")
171
    answer = eval(answer)
172
    sc.delete(0, END)
173
    sc.insert(0, answer)
174

175

176
# Initialising the user interface of the calculator
177
class Calculator:
178
    def __init__(self, txt, r, c, funcName, color="black"):
179
        self.var = Button(root, text=txt, padx=3, pady=5,
180
                          fg="white", bg=color, width=10, font="cosmicsansms 12")
181
        self.var.bind("<Button-1>", funcName)
182
        self.var.grid(row=r, column=c)
183

184

185
# Adding labels on the different buttons with name, color, function, and indexes
186

187
# Trignometric fuctions
188

189
btn0 = Calculator("sin", 1, 0, scientificCalc, "grey")
190

191
btn1 = Calculator("cos", 1, 1, scientificCalc, "grey")
192

193
btn2 = Calculator("tan", 1, 2, scientificCalc, "grey")
194

195

196
# Logarithmic functions
197

198
btn3 = Calculator("log", 1, 3, scientificCalc)
199

200
btn4 = Calculator("ln", 1, 4, scientificCalc)
201

202

203
# Brackets
204

205
btn5 = Calculator("(", 2, 0, click)
206

207
btn6 = Calculator(")", 2, 1, click)
208

209

210
# Exponential functions
211

212
btn7 = Calculator("^", 2, 2, click)
213

214
btn8 = Calculator("√", 2, 3, scientificCalc)
215

216
btn9 = Calculator("!", 2, 4, scientificCalc)
217

218

219
# Constant and Angular functions
220

221
btn10 = Calculator("π", 3, 0, scientificCalc, "blue")
222

223
btn11 = Calculator("1/x", 3, 1, scientificCalc)
224

225
btn12 = Calculator("deg", 3, 2, scientificCalc)
226

227
btn13 = Calculator("rad", 3, 3, scientificCalc)
228

229
btn14 = Calculator("e", 3, 4, scientificCalc, "blue")
230

231

232
# Basic Arithmetic operators
233

234
btn15 = Calculator("/", 4, 0, click, "#DBA800")
235

236
btn16 = Calculator("*", 4, 1, click, "#DBA800")
237

238
btn17 = Calculator("-", 4, 2, click, "#DBA800")
239

240
btn18 = Calculator("+", 4, 3, click, "#DBA800")
241

242
btn19 = Calculator("%", 4, 4, click, "#DBA800")
243

244

245
# Numbering Buttons
246

247
btn20 = Calculator("9", 5, 0, click)
248

249
btn21 = Calculator("8", 5, 1, click)
250

251
btn22 = Calculator("7", 5, 2, click)
252

253
btn23 = Calculator("6", 5, 3, click)
254

255
btn24 = Calculator("5", 5, 4, click)
256

257
btn25 = Calculator("4", 6, 0, click)
258

259
btn26 = Calculator("3", 6, 1, click)
260

261
btn27 = Calculator("2", 6, 2, click)
262

263
btn28 = Calculator("1", 6, 3, click)
264

265
btn29 = Calculator("0", 6, 4, click)
266

267

268
# Some special buttons
269

270
btn30 = Calculator("C", 7, 0, clr, "red")
271

272
btn31 = Calculator("⌦", 7, 1, backspace, "red")
273

274
btn32 = Calculator("00", 7, 2, click)
275

276
btn33 = Calculator(".", 7, 3, click)
277

278
btn34 = Calculator("=", 7, 4, calculate)
279

280
# Program Starts
281
root.mainloop()
282

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.