Creating calculator with Python
I have a task where I have to make simple python calculator using python
and I'm a bit stuck here. My calculator doesn't seem to work when I use
the equals button,it's not registering when I click it and it's not adding
or subtracting the two numbers. Any help would be great. This is my code
so far:
from tkinter import *
import tkinter.messagebox as mb
class NumberButton(Button):
def __init__(self, parent, number, display):
Button.__init__(self, parent, text=number, command=self.fillDisplay)
self.value = number
self.display = display
def fillDisplay(self):
curr_value = self.display.get()
if curr_value == '0':
new_value = str(self.value)
elif curr_value == '+':
new_value = ''.join([curr_value, str(self.value)])
else:
new_value = ''.join([curr_value, str(self.value)])
self.display.delete(0, END)
self.display.insert(0, new_value)
class ArithmeticButton(Button):
def __init__(self, parent, value, display):
Button.__init__(self, parent, text=value, command=self.doArithmetic)
self.display = display
self.value = value
def doArithmetic(self):
old_value = self.display.get()
if len(old_value) > 3:
mb.showinfo("Warning!", "This calculator cannot deal with numbers over 3
digits!")
else:
self.display.delete(0, END)
self.display.insert(0, self.value)
def explain():
mb.showinfo("Info", "This is a simple calculator interface which can add
and subtract values up to 999.")
def clearDisplay():
EntryBox.delete(0, END)
EntryBox.insert(0, '0')
root = Tk()
root.geometry("175x140")
root.title("Calculator")
menubar = Menu(root)
menubar.add_command(label="Info", command=explain)
EntryBox = Entry(root, width=7)
EntryBox.grid(row=0, columnspan=3)
EntryBox.insert(0, '0')
number = dict()
number[0] = NumberButton(root, 0, EntryBox).grid(row=4, sticky=W)
for x in range(7, 10):
number[x] = NumberButton(root, x, EntryBox).grid(row=1, column=(x-7),
sticky=W)
for x in range(4, 7):
number[x] = NumberButton(root, x, EntryBox).grid(row=2, column=(x-4),
sticky=W)
for x in range(1, 4):
number[x] = NumberButton(root, x, EntryBox).grid(row=3, column=(x-1),
sticky=W)
ArithmeticButton(root, "+", EntryBox).grid(row=4, column=2, sticky=W)
ArithmeticButton(root, "-", EntryBox).grid(row=4, column=1, sticky=W)
Button(root, text="=").grid(row=0, column=5, rowspan=2, columnspan=2,
stick=S)
Button(root, text="Clear", height=2, command=clearDisplay).grid(row=2,
column=5, rowspan=2, columnspan=2, stick=N)
root.config(menu=menubar)
mainloop()
No comments:
Post a Comment