I am currently working on a calculator program. I have managed to make the validation code function so the entry widget only receives values from valid_input
list. Although, I am currently trying to prevent inputs such as "5**2" and "2//2", is there a way to use the validation code or test_input
function to make the user unable to enter in two of the same operators. This is mainly regarding the division and multiplication operator.
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)
print(result) #Just for reference
return True
except:
messagebox.showerror("Error", "Math Error", parent = root)
#This function dosen't allow the user to input invalid values
def test_input(value, action):
#list of inputs that is valid for the calculator to function
valid_input = ["7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "/"]
if action == "1": #If an insertion is occuring in the entry
return all(char in valid_input for char in value)
# if action != 1, allow it
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()