0

I'm somewhat new to python but have just recently started working with tkinter and exceptions. I have a script that returns the index entry to an output box based on user entering 0-2 in the text box. If I enter an invalid value like 'a' there will be an exception and i want that exception to be displayed in the output box. I tried using my usual try /except approach with no luck, any tips?

from tkinter import *


window=Tk()

choice=['Apple','book','cat']


l1=Label(window,text="Enter index 0-2")
l1.grid(row=0,column=0)


option=IntVar()
e1=Entry(window,textvariable=option)
e1.grid(row=0,column=1)

try:

    def click():
       i=option.get()
       output.delete(0.0, END)
       output.insert(END, choice[i])


    output=Text(window,heigh=6,width=85,wrap=WORD)
    output.grid(row=4,column=3,rowspan=6,columnspan=2)
    #define buttons
    b1=Button(window,text="run",width=12,command=click) #command=click
    b1.grid(row=3,column=3)

except Exception as e:
    output.insert(END,("Error occured with execution: {0}".format(e))
1
  • FWIW, the index of a text widget is a string rather than a floating point number, and the index of the first character is "1.0". Commented Jan 5, 2020 at 5:07

1 Answer 1

2

A operation which can raise exception(or we expect that will raise exception) are placed inside the try clause and the code that handles exception is written in except clause.

your code should look like:

def click():
   choice = ['Apple', 'book', 'cat']
   try:
       i=option.get()
       output.delete(0.0, END)
       output.insert(END, choice[i])
   except Exception as e:
       output.insert(END,("Error occured with execution: {0}".format(e)))

window=Tk()

l1=Label(window,text="Enter index 0-2")
l1.grid(row=0,column=0)


option=IntVar()
e1=Entry(window,textvariable=option)
e1.grid(row=0,column=1)

output=Text(window,heigh=6,width=85,wrap=WORD)
output.grid(row=4,column=3,rowspan=6,columnspan=2)
#define buttons
b1=Button(window,text="run",width=12,command=click) #command=click
b1.grid(row=3,column=3)

window.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.