paulin.pommier
9 months ago
commit
16d121a879
1 changed files with 62 additions and 0 deletions
@ -0,0 +1,62 @@ |
|||||
|
import tkinter as tk |
||||
|
|
||||
|
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] |
||||
|
|
||||
|
def evaluate_expression(): |
||||
|
expression_text = entry.get() |
||||
|
if expression_text: |
||||
|
npi_list = expression_text.split() |
||||
|
try: |
||||
|
expression_tree = npi2tree(npi_list) |
||||
|
result.set(expression_tree.evaluate()) |
||||
|
except Exception as e: |
||||
|
result.set("Erreur: " + str(e)) |
||||
|
else: |
||||
|
result.set("Veuillez entrer une expression") |
||||
|
|
||||
|
root = tk.Tk() |
||||
|
root.title("Mini Calculatrice") |
||||
|
|
||||
|
expression_label = tk.Label(root, text="Expression:") |
||||
|
expression_label.pack() |
||||
|
|
||||
|
entry = tk.Entry(root) |
||||
|
entry.pack() |
||||
|
|
||||
|
calculate_button = tk.Button(root, text="Calculer", command=evaluate_expression) |
||||
|
calculate_button.pack() |
||||
|
|
||||
|
result = tk.StringVar() |
||||
|
result_label = tk.Label(root, textvariable=result) |
||||
|
result_label.pack() |
||||
|
|
||||
|
root.mainloop() |
Loading…
Reference in new issue