В функции проверки вы можете разделить логику для вставки числа и ввода оператора / точки.
Так как вы заботитесь о том, что уже есть в записи и месте, где вы вставляете символ, вы должны передать некоторую дополнительную информацию validatecommand
. Вам понадобится информация ( из этого ответа ):
# %i = index of char string to be inserted/deleted, or -1
# %s = value of entry prior to editing
# %S = the text string being inserted or deleted, if any
Затем вы можете сделать несколько проверок, чтобы запретить все, что вставило бы два оператора или указывало бы за другим:
def test_input(insert, content, index, action):
#list of inputs that is valid for the calculator to function
valid_numbers = ["7", "8", "9", "4", "5", "6", "1", "2", "3", "0"]
valid_chars = ["+", "-", "*", ".", "/"]
index = int(index)
if action != "1": # Always allow if it's not an insert
return True
if insert in valid_numbers: # Always allow a number
return True
if insert in valid_chars: # If it's an operator or point do further checks
if index==0: # Disallow if it's the first character
return False
if content[index-1] in valid_chars: # Disallow if the character before is an operator or point
return False
if index != len(content): # If you're not at the end
if content[index] in valid_chars: # Disallow if the next character is an operator or point
return False
return True # Allow if it's none of the above
else:
return False # Disallow if the character is not a number, operator or point
с
display.configure(validatecommand = (display.register(test_input), "%S", "%s", "%i", "%d"))
Я забыл, что это неправильно вводит ответ, поскольку я предполагаю, что за один раз вставляется только один символ. Вы можете исправить это (по крайней мере) двумя способами:
Вы можете отключить проверку для вставки ответа и включить его снова, когда вставили:
display.configure(validate='none')
display.insert(0, text)
display.configure(validate='key')
Или, поскольку ответы всегда являются всеми числами, вы можете изменить второе if
в команде проверки, чтобы разрешить использование нескольких чисел вместо одного:
if all(char in valid_numbers for char in insert):