Пишем калькулятор на python и делаем из него полноценное приложение Windows

Для тех кто убил калькулятор на своей винде (как я). Пишем свой калькулятор на python в одном файле и делаем из него полноценное приложение Windows.

PYTHON
import tkinter as tk
from tkinter import ttk
import math

class MatrixCalculator:
def __init__(self):
self.root = tk.Tk()
self.root.title("Matrix Calculator")
self.root.configure(bg='#0a0a0a')
self.root.attributes('-alpha', 0.92)

self.base_font_size = 14
self.base_width = 400
self.base_height = 550

self.root.minsize(self.base_width, self.base_height)
self.is_fullscreen = False

self.current_input = ""
self.history_text = ""

self.setup_ui()
self.setup_bindings()

def get_scaled_size(self, base_size):
screen_width = self.root.winfo_screenwidth()
scale_factor = screen_width / 1920
return max(int(base_size * scale_factor), base_size)

def setup_ui(self):
self.current_font_size = self.get_scaled_size(self.base_font_size)
self.display_font_size = self.get_scaled_size(20)

colors = {
'bg': '#0a0a0a',
'display_bg': '#1a1a1a',
'display_fg': '#e8e8e8',
'button_bg': '#2a2a2a',
'button_fg': '#ffffff',
'button_active': '#3a3a3a',
'operator_bg': '#404040',
'operator_fg': '#ffffff',
'equals_bg': '#505050',
'history_fg': '#aaaaaa'
}

top_frame = tk.Frame(self.root, bg=colors['bg'])
top_frame.pack(fill='x', padx=15, pady=8)

self.history_label = tk.Label(top_frame, text="", fg=colors['history_fg'],
bg=colors['bg'], font=('Arial', self.current_font_size-2),
anchor='e')
self.history_label.pack(side='left', fill='x', expand=True)

transparency_frame = tk.Frame(top_frame, bg=colors['bg'])
transparency_frame.pack(side='right')

tk.Label(transparency_frame, text="◉", fg=colors['history_fg'],
bg=colors['bg'], font=('Arial', 10)).pack(side='left')

self.alpha_var = tk.DoubleVar(value=0.92)
alpha_scale = ttk.Scale(transparency_frame, from_=0.4, to=1.0,
variable=self.alpha_var, command=self.update_alpha,
orient='horizontal', length=70)
alpha_scale.pack(side='left', padx=5)

self.display = tk.Entry(self.root, font=('Arial', self.display_font_size, 'bold'),
justify='right', bg=colors['display_bg'], fg=colors['display_fg'],
insertbackground=colors['display_fg'], bd=0, relief='flat')
self.display.pack(fill='x', padx=15, pady=(0, 15), ipady=10)

buttons_frame = tk.Frame(self.root, bg=colors['bg'])
buttons_frame.pack(fill='both', expand=True, padx=15, pady=(0, 15))

buttons = [
('%', 'special'), ('√', 'special'), ('x²', 'special'), ('1/x', 'special'),
('CE', 'clear'), ('C', 'clear'), ('⌫', 'clear'), ('÷', 'operator'),
('7', 'digit'), ('8', 'digit'), ('9', 'digit'), ('×', 'operator'),
('4', 'digit'), ('5', 'digit'), ('6', 'digit'), ('-', 'operator'),
('1', 'digit'), ('2', 'digit'), ('3', 'digit'), ('+', 'operator'),
('±', 'special'), ('0', 'digit'), ('.', 'digit'), ('=', 'equals')
]

button_styles = {
'digit': {'bg': colors['button_bg'], 'fg': colors['button_fg'], 'active': colors['button_active']},
'operator': {'bg': colors['operator_bg'], 'fg': colors['operator_fg'], 'active': colors['button_active']},
'special': {'bg': colors['button_bg'], 'fg': '#e8b010', 'active': colors['button_active']},
'clear': {'bg': '#5a2a2a', 'fg': '#ff6b6b', 'active': '#6a3a3a'},
'equals': {'bg': colors['equals_bg'], 'fg': colors['button_fg'], 'active': colors['button_active']}
}

row, col = 0, 0
for btn_text, btn_type in buttons:
style = button_styles[btn_type]
cmd = lambda x=btn_text: self.button_click(x)

btn = tk.Button(buttons_frame, text=btn_text,
font=('Arial', self.current_font_size, 'bold'),
bg=style['bg'], fg=style['fg'],
activebackground=style['active'],
activeforeground=style['fg'],
bd=0, relief='flat', cursor='hand2',
command=cmd)
btn.grid(row=row, column=col, sticky='nsew', padx=2, pady=2)

if btn_text == '0':
btn.grid(columnspan=2, sticky='nsew')
col += 1

col += 1
if col > 3:
col = 0
row += 1

for i in range(6):
buttons_frame.grid_rowconfigure(i, weight=1)
for i in range(4):
buttons_frame.grid_columnconfigure(i, weight=1)

def setup_bindings(self):
self.root.bind('', self.toggle_fullscreen)
self.root.bind('', self.exit_fullscreen)

for key in '0123456789':
self.root.bind(f'', lambda e, k=key: self.button_click(k))

self.root.bind('', lambda e: self.button_click('+'))
self.root.bind('', lambda e: self.button_click('-'))
self.root.bind('', lambda e: self.button_click('×'))
self.root.bind('', lambda e: self.button_click('÷'))
self.root.bind('', lambda e: self.button_click('.'))
self.root.bind('', lambda e: self.button_click('='))
self.root.bind('', lambda e: self.button_click('='))
self.root.bind('', lambda e: self.button_click('⌫'))
self.root.bind('', lambda e: self.button_click('CE'))
self.root.bind('', lambda e: self.button_click('C'))

def update_alpha(self, value):
self.root.attributes('-alpha', float(value))

def toggle_fullscreen(self, event=None):
self.is_fullscreen = not self.is_fullscreen
self.root.attributes('-fullscreen', self.is_fullscreen)

def exit_fullscreen(self, event=None):
self.is_fullscreen = False
self.root.attributes('-fullscreen', False)

def button_click(self, symbol):
if symbol == '=':
self.calculate()
elif symbol == 'C':
self.clear()
elif symbol == 'CE':
self.clear_entry()
elif symbol == '⌫':
self.backspace()
elif symbol == '±':
self.plus_minus()
elif symbol == 'x²':
self.square()
elif symbol == '√':
self.square_root()
elif symbol == '1/x':
self.reciprocal()
elif symbol == '%':
self.percentage()
else:
self.current_input += str(symbol)
self.display.delete(0, tk.END)
self.display.insert(0, self.current_input)

if symbol not in ['=', 'C', 'CE', '⌫']:
self.history_text += symbol
self.history_label.config(text=self.history_text[-40:])

def calculate(self):
try:
expression = self.current_input.replace('×', '*').replace('÷', '/')
result = eval(expression)

if result == int(result):
result = int(result)
else:
result = round(result, 10)

self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_input = str(result)
self.history_text += f"={result}"
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")
self.current_input = ""

def clear(self):
self.current_input = ""
self.history_text = ""
self.display.delete(0, tk.END)
self.history_label.config(text="")

def clear_entry(self):
self.current_input = ""
self.display.delete(0, tk.END)

def backspace(self):
self.current_input = self.current_input[:-1]
self.history_text = self.history_text[:-1]
self.display.delete(0, tk.END)
self.display.insert(0, self.current_input)
self.history_label.config(text=self.history_text)

def plus_minus(self):
if self.current_input:
if self.current_input[0] == '-':
self.current_input = self.current_input[1:]
else:
self.current_input = '-' + self.current_input
self.display.delete(0, tk.END)
self.display.insert(0, self.current_input)

def square(self):
try:
result = float(self.current_input) ** 2
result = int(result) if result == int(result) else round(result, 10)
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_input = str(result)
self.history_text += f"²={result}"
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")

def square_root(self):
try:
result = math.sqrt(float(self.current_input))
result = int(result) if result == int(result) else round(result, 10)
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_input = str(result)
self.history_text += f"√={result}"
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")

def reciprocal(self):
try:
result = 1 / float(self.current_input)
result = int(result) if result == int(result) else round(result, 10)
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_input = str(result)
self.history_text += f"¹/ₓ={result}"
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")

def percentage(self):
try:
result = float(self.current_input) / 100
result = int(result) if result == int(result) else round(result, 10)
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_input = str(result)
self.history_text += f"%={result}"
except:
self.display.delete(0, tk.END)
self.display.insert(0, "Error")

def run(self):
self.root.mainloop()

if __name__ == "__main__":
calc = MatrixCalculator()
calc.run()

bash

POWERSHELL
pip install pyinstaller
pyinstaller --onefile --windowed --name "MatrixCalculator" calculator.py
Предыдущая запись
Установка Notepad++ через PowerShell
Следующая запись
Создаём флешку для востановления Windows 11 через утилиту DiskPart (ручной метод)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Заполните поле
Заполните поле
Пожалуйста, введите корректный адрес email.
Вы должны согласиться с условиями для продолжения