You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6 KiB

class Expression:
def __init__(self, root, left, right):
self.root = root
self.left = left
self.right = right
def evaluate(self):
if self.root == '+':
return self.left.evaluate() + self.right.evaluate()
elif self.root == '*':
return self.left.evaluate() * self.right.evaluate()
else:
return int(self.root)
def __str__(self):
if self.root in ['+', '*']:
return f'({self.left} {self.root} {self.right})'
else:
return str(self.root)
def npi2tree(npi_list):
stack = []
for item in npi_list:
if item in ['+', '*']:
right = stack.pop()
left = stack.pop()
stack.append(Expression(item, left, right))
else:
stack.append(Expression(item, None, None))
return stack[0]
import tkinter as tk
def evaluate_expression():
expression_text = entry.get()
npi_list = expression_text.split()
expression_tree = npi2tree(npi_list)
result.set(expression_tree.evaluate())
root = tk.Tk()
root.configure(bg="orange")
root.title("Mini Calculatrice")
expression_label = tk.Label(root, text="Expression:")
expression_label.pack()
expression_label.configure(bg="beige")
entry = tk.Entry(root)
entry.pack()
calculate_button = tk.Button(root, text="Calculer", command=evaluate_expression)
calculate_button.configure(bg="beige")
calculate_button.pack()
result = tk.StringVar()
result_label = tk.Label(root, textvariable=result)
result_label.configure(bg="orange")
result_label.pack()
root.mainloop()