Gui python tkinter калькулятор
- Python | Simple GUI calculator using Tkinter
- Create Table Using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python: Weight Conversion GUI using Tkinter
- Python: Age Calculator using Tkinter
- Python | Create a GUI Marksheet using Tkinter
- Python | Loan calculator using Tkinter
- Python | Create a digital clock using Tkinter
- Make Notepad using Tkinter
- Color game using Tkinter in Python
- Python | Simple FLAMES game using Tkinter
- Simple registration form using Python Tkinter
- How to create a COVID19 Data Representation GUI?
Introduction
Widgets
- Python | Creating a button in tkinter
- Python | Add style to tkinter button
- Python | Add image on a Tkinter button
- Python Tkinter – Label
- Python Tkinter | Create LabelFrame and add widgets to it
- RadioButton in Tkinter | Python
- Python Tkinter – Checkbutton Widget
- Python Tkinter – Canvas Widget
- Python Tkinter | Create different shapes using Canvas class
- Python Tkinter | Create different type of lines using Canvas class
- Python Tkinter | Moving objects using Canvas.move() method
- Combobox Widget in tkinter | Python
- maxsize() method in Tkinter | Python
- minsize() method in Tkinter | Python
- resizable() method in Tkinter | Python
- Python Tkinter – Entry Widget
- Tkinter – Read only Entry Widget
- Python Tkinter – Text Widget
- Python Tkinter – Message
- Python | Menu widget in Tkinter
- Python Tkinter – Menubutton Widget
- Python Tkinter – SpinBox
- Progressbar widget in Tkinter | Python
- Python-Tkinter Scrollbar
- Python Tkinter – ScrolledText Widget
- Python Tkinter – ListBox Widget
- Scrollable ListBox in Python-tkinter
- Python Tkinter – Frame Widget
- Scrollable Frames in Tkinter
- How to make a proper double scrollbar frame in Tkinter
- Python Tkinter – Scale Widget
- Hierarchical treeview in Python GUI application
- Python-Tkinter Treeview scrollbar
- Python Tkinter – Toplevel Widget
- Python | askopenfile() function in Tkinter
- Python | asksaveasfile() function in Tkinter
- Python – Tkinter askquestion Dialog
- Python Tkinter – MessageBox Widget
- Create a Yes/No Message Box in Python using tkinter
- Change the size of MessageBox – Tkinter
- Different messages in Tkinter | Python
- Change Icon for Tkinter MessageBox
- Python – Tkinter Choose color Dialog
- Popup Menu in Tkinter
Geometry Management
Binding Functions
Working with Images in Tkinter
Tkinter Advance
- Getting screen’s height and width using Tkinter | Python
- Python | How to dynamically change text of Checkbutton
- Python | focus_set() and focus_get() method
- Search String in Text using Python-Tkinter
- Autocomplete ComboBox in Python-Tkinter
- Autohiding Scrollbars using Python-tkinter
- Python Tkinter – Validating Entry Widget
- Tracing Tkinter variables in Python
- Python | setting and retrieving values of Tkinter variable
- Tkinter | Adding style to the input text using ttk.Entry widget
- Python | after method in Tkinter
- destroy() method in Tkinter | Python
- Text detection using Python
- Python | winfo_ismapped() and winfo_exists() in Tkinter
- Collapsible Pane in Tkinter | Python
- Creating a multiple Selection using Tkinter
- Creating Tabbed Widget With Python-Tkinter
- Open a new Window with a button in Python-Tkinter
- Cryptography GUI using python
- Python | Simple GUI calculator using Tkinter
- Create Table Using Tkinter
- Python | GUI Calendar using Tkinter
- File Explorer in Python using Tkinter
- Python | ToDo GUI Application using Tkinter
- Python: Weight Conversion GUI using Tkinter
- Python: Age Calculator using Tkinter
- Python | Create a GUI Marksheet using Tkinter
- Python | Loan calculator using Tkinter
- Python | Create a digital clock using Tkinter
- Make Notepad using Tkinter
- Color game using Tkinter in Python
- Python | Simple FLAMES game using Tkinter
- Simple registration form using Python Tkinter
- How to create a COVID19 Data Representation GUI?
Калькулятор с графическим интерфейсом с помощью 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()