App 5: Desktop App with Windows & Buttons / Build a calculator
Lesson 6 of 10
Clear, errors and keyboard
Add a C button to clear, show 'Error' for dividing by zero, and bind keyboard keys so people can type sums.
Key points
- root.bind("<Key>", handler)
- except ZeroDivisionError
- Return key = equals
def calculate():
try:
result = safe_eval(entry.get())
except (ValueError, SyntaxError, ZeroDivisionError):
result = "Error"
entry.delete(0, tk.END)
entry.insert(0, str(result))
root.bind("<Return>", lambda e: calculate())Your turn
Add a C button and make Enter calculate.
Quiz · +10 XP
Which exception happens when you divide by zero?
Log in to save progress and earn XP.