Home > database >  Python Tkinter - how to create an error message box for my calculator app
Python Tkinter - how to create an error message box for my calculator app

Time:04-05

I'm making a calculator with Python and Tkinter and I'm having problems with my calculator.

I'm trying to create an error message box wherein if there are double operations bundled together (ex. '--', ' -'), the message would pop up. I'm basically trying to add a restriction to my program, but I don't know how to implement this. I just can't seem to get the try/except block code correct and I'm having problems on where to put it. I apologize if this seems like an easy question to someone. It's because I'm new to the field of programming.

Here's my code:

from tkinter import *
from PIL import Image, ImageTk
from tkinter import messagebox


# base
window = Tk()
window.title('Calculator')
window.geometry('258x455')
icon = ImageTk.PhotoImage(file='icon.png')
window.iconphoto(True, icon)
window.resizable(0, 0)
base_frame = Frame(window, bg='#292929', width=300, height=455)
window.config(background='#292929')

# functions


def btn_press(item):
    global expression
    expression = expression   str(item)
    input_text.set(expression)


def clear():
    global expression
    expression = ''
    input_text.set('')


def equal():
    global expression
    result = str(eval(expression))
    input_text.set(result)
    expression = ''

try:
    # what code should I put in
    # and where should I put my try/except code

except SyntaxError: 
    messagebox.showerror('Calculation Error', 'You cannot bundle two or more operations together.')


input_text = StringVar()
expression = ''

CodePudding user response:

It should be around the code that calculates the result.

def equal():
    global expression
    try:
        result = str(eval(expression))
        input_text.set(result)
        expression = ''
    except SyntaxError:
        messagebox.showerror('Calculation Error', 'You cannot bundle two or more operations together.')
  • Related