coding cp1251 from __future__ import division from Tkinter import from

  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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#-*- coding:cp1251 -*-
from __future__ import division
from Tkinter import *
from tkMessageBox import showerror, askokcancel
from math import *
# ----цвета----
LIGHTGREY = '#6e6e6e'
GREY = '#303030'
BLACK = '#000000'
WHITE = '#ffffff'
ORANGE = '#ffb75f'
RED = '#ff0000'
def press(symbol):
entry.insert(END, str(symbol))
def copy(event=None):
obj = entry.get()
root.clipboard_clear()
root.clipboard_append(obj)
def paste(event=None):
entry.insert(END, root.clipboard_get())
def cut(event=None):
obj = entry.get()
root.clipboard_clear()
root.clipboard_append(obj)
entry.delete(0, END)
def func_input(function):
if entry.get() == '':
showerror(u'Ошибка', u'Сначала необходимо\nввести выражение.')
else:
entry.insert(0, function+'(')
press(')')
equal() # после вставки ф-ции результат сразу отображается
def backspace():
expression = entry.get()
entry.delete(0, END)
entry.insert(END, expression[0:-1])
def c(event=None):
sv.set('')
entry.delete(0, END)
def up():
result = sv.get()
if result == '':
pass
else:
entry.delete(0, END)
entry.insert(END, result)
def bye():
if not askokcancel(u"Выход", u"Может еще что-нибудь посчитаем?"):
root.destroy()
def equal(event=None):
expression = entry.get()
try:
result = eval(expression)
except ZeroDivisionError:
showerror(u'Ошибка', u'На ноль\nделить нельзя.')
return
except (SyntaxError, NameError), exc:
_L = str(exc)
showerror(u'Ошибка', _L[:-18])
return
# --- блок для отбрасывания нуля у float, пример: 1.0 заменяется на 1 --
if type(result) == type(0.0):
if result == int(result): result = int(result)
# --- блок завершён ---
result = str(result)
sv.set(str(result))
root = Tk()
root.title("PyCalculator")
root.protocol("WM_DELETE_WINDOW", bye)
root.resizable(0, 0)
root.bind('<Escape>', exit)
sv = StringVar()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label=u"Файл", menu=filemenu)
filemenu.add_command(label=u"Очистить Ctrl+C", command=c)
filemenu.add_separator()
filemenu.add_command(label=u"Выход Esc", command=exit)
inp_menu = Menu(menu)
menu.add_cascade(label=u"Вставка", menu=inp_menu)
for _func in ['DEGREES', 'RADIANS', 'SIN', 'COS', 'TAN', 'SQRT']:
inp_menu.add_command(label=_func,
command = (lambda func: lambda: func_input(func))(_func.lower()))
frame = Frame(root, background=ORANGE)
frame.pack()
entry = Entry(frame, text='', width=27, bg=RED, fg=BLACK, font=("Arial", 20, "bold"))
entry.bind('<Return>', equal)
entry.bind('<Control-c>', c)
entry.bind('<Control-ntilde>', c) # для русской раскладки 'c'
entry.bind("<Button-3>", (lambda event: entrymenu.post(event.x_root, event.y_root)))
entry.grid(row=0, column=0, columnspan=6)
entrymenu = Menu(root, tearoff=0)
entrymenu.add_command(label=u"Вырезать всё", command=cut)
entrymenu.add_command(label=u"Копировать всё", command=copy)
entrymenu.add_command(label=u"Вставить", command=paste)
Label(frame, text=u'результат:', width=8, bg=ORANGE,
font=("Arial", 14, "bold")).grid(row=1, column=0, columnspan=2)
Label(frame, textvariable=sv, width=25, bg=ORANGE,
font=("Arial", 12, "bold")).grid(row=1, column=2, columnspan=4)
# кнопки
btns = []
input_btns = range(10) + ['.']
cmd_btns = ['+', '-', '*', '/', '(', ')', 'Back', 'C', 'Up', '=']
for symbol in input_btns + cmd_btns:
btns.append(Button(frame,
text = str(symbol),
borderwidth = 6,
width = 3,
foreground = WHITE,
activeforeground = WHITE,
background = GREY,
activebackground = GREY,
font = ('Comic Sans MS', 17, 'bold'),
command = (lambda s: lambda: press(s))(symbol))) # жесть
btns[0]['width'] = 8
btns[11]['height'] = 3
btns[18]['command'] = c
btns[17].config(width=8, command=backspace)
btns[19]['command'] = up
btns[20]['command'] = equal
for i in range(11):
btns[i].config(background = LIGHTGREY,
activebackground = LIGHTGREY)
btns[0].grid(row=5, column=0, columnspan=2, pady=2)
btns[1].grid(row=4, column=0, pady=2)
btns[2].grid(row=4, column=1)
btns[3].grid(row=4, column=2)
btns[4].grid(row=3, column=0, pady=2)
btns[5].grid(row=3, column=1)
btns[6].grid(row=3, column=2)
btns[7].grid(row=2, column=0, pady=2)
btns[8].grid(row=2, column=1)
btns[9].grid(row=2, column=2)
btns[10].grid(row=5, column=2) # точка
btns[11].grid(row=4, column=3, rowspan=2) # +
btns[12].grid(row=5, column=4) # -
btns[13].grid(row=3, column=3) # *
btns[14].grid(row=3, column=4) # /
btns[15].grid(row=4, column=4) # (
btns[16].grid(row=4, column=5) # )
btns[17].grid(row=2, column=3, columnspan=2) # Back
btns[18].grid(row=2, column=5) # С
btns[19].grid(row=3, column=5) # Up
btns[20].grid(row=5, column=5) # =
root.mainloop()