Pull to refresh

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

Здраствуйте. В данной статье хочу поделиться с вами калькулятором на Пайтон. Итак, приступим. (Извините, если что что-то не так, это моя первая статья, да и в программировании я почти 0)

Сначало всё по стандарту. Импортируем библиотеки. Использовать мы будем сам 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()
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.