Открыть калькулятор на python

Калькулятор на python

Здравствуйте, в предыдущей статье я показывал как сделать игру на python, а сейчас мы посмотри как сделать простой калькулятор на python tkinter.

Создаём окно 485 на 550. Размеры не важны, мне понравились такие. Так же указываем, что окно не будет изменяться.

from tkinter import * class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.build() def build(self): pass def logicalc(self, operation): pass def update(): pass if __name__ == '__main__': root = Tk() root["bg"] = "#000" root.geometry("485x550+200+200") root.title("Калькулятор") root.resizable(False, False) app = Main(root) app.pack() root.mainloop() 

Делаем кнопочки

В методе build создаём такой список:

btns = [ "C", "DEL", "*", "=", "1", "2", "3", "/", "4", "5", "6", "+", "7", "8", "9", "-", "+/-", "0", "%", "X^2" ] 

Он отвечает за все кнопки, отображающиеся у нас в окне.

Мы создали список, теперь проходимся циклом и отображаем эти кнопки. Для этого в том же методе пишем следующее:

x = 10 y = 140 for bt in btns: com = lambda x=bt: self.logicalc(x) Button(text=bt, bg="#FFF", font=("Times New Roman", 15), command=com).place(x=x, y=y, width=115, height=79) x += 117 if x > 400: x = 10 y += 81 

Замечательно, у нас есть кнопочки. Добавляем надпись с выводом результата. Я хочу что бы текст был слева, следовательно, аттрибутов выравнивания текста писать не нужно.

self.formula = "0" self.lbl = Label(text=self.formula, font=("Times New Roman", 21, "bold"), bg="#000", foreground="#FFF") self.lbl.place(x=11, y=50) 

Пишем логику

def logicalc(self, operation): if operation == "C": self.formula = "" elif operation == "DEL": self.formula = self.formula[0:-1] elif operation == "X^2": self.formula = str((eval(self.formula))**2) elif operation == "=": self.formula = str(eval(self.formula)) else: if self.formula == "0": self.formula = "" self.formula += operation self.update() def update(self): if self.formula == "": self.formula = "0" self.lbl.configure(text=self.formula) 

Так, как у нас нет ввода с клавиатуры, мы можем позволить себе сделать так, просто проверить на спец. кнопки (C, DEL, =) и в остальных случаях просто добавить это к формуле.

Читайте также:  Php function in twig template

У этого калькулятора множество недочетов, но мы и не стремились сделать его идеальным.

Полный код моей версии калькулятора:

from tkinter import * class Main(Frame): def __init__(self, root): super(Main, self).__init__(root) self.build() def build(self): self.formula = "0" self.lbl = Label(text=self.formula, font=("Times New Roman", 21, "bold"), bg="#000", foreground="#FFF") self.lbl.place(x=11, y=50) btns = [ "C", "DEL", "*", "=", "1", "2", "3", "/", "4", "5", "6", "+", "7", "8", "9", "-", "(", "0", ")", "X^2" ] x = 10 y = 140 for bt in btns: com = lambda x=bt: self.logicalc(x) Button(text=bt, bg="#FFF", font=("Times New Roman", 15), command=com).place(x=x, y=y, width=115, height=79) x += 117 if x > 400: x = 10 y += 81 def logicalc(self, operation): if operation == "C": self.formula = "" elif operation == "DEL": self.formula = self.formula[0:-1] elif operation == "X^2": self.formula = str((eval(self.formula))**2) elif operation == "=": self.formula = str(eval(self.formula)) else: if self.formula == "0": self.formula = "" self.formula += operation self.update() def update(self): if self.formula == "": self.formula = "0" self.lbl.configure(text=self.formula) if __name__ == '__main__': root = Tk() root["bg"] = "#000" root.geometry("485x550+200+200") root.title("Калькулятор") root.resizable(False, False) app = Main(root) app.pack() root.mainloop() 

Источник

Калькулятор с графическим интерфейсом с помощью tkinter

Сначало всё по стандарту. Импортируем библиотеки. Использовать мы будем сам tkinter и библиотеку математических функций math.

from tkinter import * from tkinter import messagebox import math

Далее задаем функции кнопок.(Я пару шагов пропустил, точнее написал после, но калькулятор от этого не сломается.):

def add_digit(digit): value = calc.get() if value[0]=='0' and len(value)==1: value = value[1:] calc.delete(0, END) calc.insert(0, value + digit) def add_operation(operation): value = calc.get() if value[-1] in '-+/*': value = value[:-1] elif '+' in value or '-' in value or'*' in value or'/' in value: calculate() value = calc.get() calc.delete(0, END) calc.insert(0, value + operation) def calculate(): value = calc.get() if value[-1] in '-+/*': value = value+value[:-1] calc.delete(0, END) try: calc.insert(0, eval(value)) except (NameError, SyntaxError): messagebox.showerror('Внимание!', 'Нужно вводить только числа и цифры!') calc.insert(0, 0) except ZeroDivisionError: messagebox.showerror('Внимание!', 'На ноль делить нельзя!') calc.insert(0, 0) def add_sqrt(): value = calc.get() value = float(value) value = math.sqrt(value) calc.delete(0, END) calc.insert(0, value) def add_fabs(): value = calc.get() value = eval(value) value = math.fabs(value) calc.delete(0, END) calc.insert(0, value) def clear(): calc.delete(0, END) calc.insert(0, 0) def make_calc_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=calculate) def make_clear_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=clear) def make_operation_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=lambda : add_operation(operation)) def make_sqrt_button(operation): return Button(text=operation, image=img, bd=5, font=('Times New Roman', 13), command=add_sqrt) def make_fabs_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=add_fabs) def make_digit_button(digit): return Button(text=digit, bd=5, font=('Times New Roman', 13), command=lambda : add_digit(digit))

Теперь создаём окно, в котором будет наш пример и ответ.

tk=Tk() tk.geometry('260x360+100+200') tk.resizable(0,0) tk.title("Калькулятор") tk['bg']='#FFC0CB' #Цвет фона - чёрный. Его можно поменять на любой другой.

Если посмотреть на оригинальный калькулятор Виндовс мы увидим, что текст располагается с правой стороны, сделаем также. Для этого в ткинтер используется функция justify :

calc = Entry(tk, justify=RIGHT, font=('Times New Roman', 15), width=15) calc.insert(0, '0') calc.place(x=15, y=20, width=220, height=30)

Следующий шаг прост. Располагаем кнопки.

make_digit_button('1').place(x=20, y=250, width=40, height=40) make_digit_button('2').place(x=80, y=250, width=40, height=40) make_digit_button('3').place(x=140, y=250, width=40, height=40) make_digit_button('4').place(x=20, y=190, width=40, height=40) make_digit_button('5').place(x=80, y=190, width=40, height=40) make_digit_button('6').place(x=140, y=190, width=40, height=40) make_digit_button('7').place(x=20, y=130, width=40, height=40) make_digit_button('8').place(x=80, y=130, width=40, height=40) make_digit_button('9').place(x=140, y=130, width=40, height=40) make_digit_button('0').place(x=20, y=310, width=100, height=40) make_digit_button('.').place(x=140, y=310, width=40, height=40) make_operation_button('+').place(x=200, y=310, width=40, height=40) make_operation_button('-').place(x=200, y=250, width=40, height=40) make_operation_button('*').place(x=200, y=190, width=40, height=40) make_operation_button('/').place(x=200, y=130, width=40, height=40)

В моей задаче было использование картинки в качестве корня, поэтому используем PhotoImage для импортировки фотографии(фотография должна быть в одной папке с кодом)

img=PhotoImage(file='radical.png') make_sqrt_button('').place(x=80, y=70, width=40, height=40)

Последние шаги по мелочам. В качестве дополнительной функции добавим модуль. Кнопку очистки всего и равно добавляем обязательно!

#Модуль числа make_fabs_button('|x|').place(x=140, y=70, width=40, height=40) #Очистка make_clear_button('C').place(x=20, y=70, width=40, height=40) #Равно make_calc_button('=').place(x=200, y=70, width=40, height=40) tk.mainloop()

Полный код выглядит как-то так:

#Бібліотека модулів from tkinter import * from tkinter import messagebox import math def add_digit(digit): value = calc.get() if value[0]=='0' and len(value)==1: value = value[1:] calc.delete(0, END) calc.insert(0, value + digit) def add_operation(operation): value = calc.get() if value[-1] in '-+/*': value = value[:-1] elif '+' in value or '-' in value or'*' in value or'/' in value: calculate() value = calc.get() calc.delete(0, END) calc.insert(0, value + operation) def calculate(): value = calc.get() if value[-1] in '-+/*': value = value+value[:-1] calc.delete(0, END) try: calc.insert(0, eval(value)) except (NameError, SyntaxError): messagebox.showinfo('Внимание!', 'Нужно вводить только числа!') calc.insert(0, 0) except ZeroDivisionError: messagebox.showinfo('Внимание!', 'На ноль делить нельзя!') calc.insert(0, 0) def add_sqrt(): value = calc.get() value = float(value) value = math.sqrt(value) calc.delete(0, END) calc.insert(0, value) def add_fabs(): value = calc.get() value = eval(value) value = math.fabs(value) calc.delete(0, END) calc.insert(0, value) def clear(): calc.delete(0, END) calc.insert(0, 0) def make_calc_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=calculate) def make_clear_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=clear) def make_operation_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=lambda : add_operation(operation)) def make_sqrt_button(operation): return Button(text=operation, image=img, bd=5, font=('Times New Roman', 13), command=add_sqrt) def make_fabs_button(operation): return Button(text=operation, bd=5, font=('Times New Roman', 13), command=add_fabs) def make_digit_button(digit): return Button(text=digit, bd=5, font=('Times New Roman', 13), command=lambda : add_digit(digit)) tk=Tk() tk.geometry('260x360+100+200') tk.resizable(0,0) tk.title("Калькулятор") tk['bg']='#FFC0CB' calc = Entry(tk, justify=RIGHT, font=('Times New Roman', 15), width=15) calc.insert(0, '0') calc.place(x=15, y=20, width=220, height=30) #Числа от 1 до 9 и точка make_digit_button('1').place(x=20, y=250, width=40, height=40) make_digit_button('2').place(x=80, y=250, width=40, height=40) make_digit_button('3').place(x=140, y=250, width=40, height=40) make_digit_button('4').place(x=20, y=190, width=40, height=40) make_digit_button('5').place(x=80, y=190, width=40, height=40) make_digit_button('6').place(x=140, y=190, width=40, height=40) make_digit_button('7').place(x=20, y=130, width=40, height=40) make_digit_button('8').place(x=80, y=130, width=40, height=40) make_digit_button('9').place(x=140, y=130, width=40, height=40) make_digit_button('0').place(x=20, y=310, width=100, height=40) make_digit_button('.').place(x=140, y=310, width=40, height=40) #Основные математические действия make_operation_button('+').place(x=200, y=310, width=40, height=40) make_operation_button('-').place(x=200, y=250, width=40, height=40) make_operation_button('*').place(x=200, y=190, width=40, height=40) make_operation_button('/').place(x=200, y=130, width=40, height=40) #Корень img=PhotoImage(file='radical.png') make_sqrt_button('').place(x=80, y=70, width=40, height=40) #Модуль make_fabs_button('|x|').place(x=140, y=70, width=40, height=40) #Кнопка очистки make_clear_button('C').place(x=20, y=70, width=40, height=40) #Равно make_calc_button('=').place(x=200, y=70, width=40, height=40) tk.mainloop()

Источник

Оцените статью