I am currently working on a basic calculator program. I am trying to use the validate function so the user is only able to enter in values from the valild_input
list. The test_input
function which contains this list works fine until I decide to type in "=" or press the equals button
. When I press the equals_button
the current equation on the display
entry isn't deleted and replaced with the result. Although this doesn't occur when I press the "=" key on the keyboard. The only issue is that the equals sign stays on the display
and after that, the entry widget stops validating the user's input altogether.
from tkinter import *
from tkinter import messagebox
def replace_text(text):
display.delete(0, END)
display.insert(0, text)
#Calculates the input in the display
def calculate(event = None):
equation = display.get()
try:
result = eval(equation)
replace_text(result)
except:
messagebox.showerror("Error", "Math Error", parent = root)
def test_input(value, action):
valid_input = ["7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/"]
if action == "1":
if value not in valid_input:
return False
return True
root = Tk()
root.title("Calculator testing")
display = Entry(root, font=("Helvetica", 16), justify = "right", validate = "key")
display.configure(validatecommand = (display.register(test_input), "%S", "%d"))
display.insert(0, "")
display.grid(column = 0, row = 0, columnspan = 4, sticky = "NSWE", padx = 10, pady = 10)
display.bind("=", calculate)
#Equals button
button_equal = Button(root, font = ("Helvetica", 14), text = "=", command =
calculate, bg = "#c0ded9")
button_equal.grid(column = 2, row = 1, columnspan = 2, sticky = "WE")
#All clear button
button_clear = Button(root, font = ("Helvetica", 14), text = "AC", command = lambda: replace_text(""), bg = "#c0ded9")
button_clear.grid(column = 0, row = 1, columnspan = 2, sticky = "WE")
#Main Program
root.mainloop()