I need to write a code that runs similar to normal calculators in such a way that it displays the first number I type in, when i press the operand, the entry widget still displays the first number, but when i press the numbers for my second number, the first one gets replaced. I'm not to the point in writing the whole code yet, but I'm stuck at the point where when I press the 2nd number(s), the first set gets replaced. I was thinking about if key == one of the operands, than I set the num on the entry as variable first, then I do ent.delete(0,end) to clear the screen and ent.insert(0,first) to display the first num in the entry widget. Now I don't know what to do to clear the entry widget when the 2nd number(s) is pressed.
+2
A:
What you need here is a concept of state. Each time a key is pressed, you check the state and determine what action to take.
In the initial state, you take input of numbers.
When an operand button is pressed, you store the operand, and change the state.
When another number is pressed, you store the number, clear the numeric input, and start the number input again.
Then when the equals button is pressed, you perform the operation, using your stored number and operand with the current number in the numeric input.
Note that with a dynamic language like Python, instead of using a variable and if statements to check the state, you can just change the function that handles key/button pressed depending on what the state is.
Ryan Ginstrom
2010-02-15 08:03:44