Python中的try-except块未处理异常

时间:2019-05-20 09:56:07

标签: python-3.x exception tkinter

我写了一个简单的python代码,可以输入用户的任何数字。如果输入了其他任何内容,则会根据代码引发异常。我将输入的值强制转换为int型,以检查它是否为整数。理想情况下,我除外,当我输入任何字母时,应引发例外情况并应打印我给出的文本。但是我仍然可以看到它没有被抓住。

但是,当我在typecast语句周围专门添加一个try-except块时,它可以工作。


from tkinter import *

window = Tk()
window.geometry('400x400')

class hangman:
    def __init__(self):
        self.entry = ''

    def clicked(self, label2):
        label2.place(x=100, y=200)

        while True:
            try:
                def get_value(event):
                    self.entry = e1.get()
                    self.entry = int(self.entry)
                    print(self.entry)

                Label(window, text="Enter any number :").place(x=10, y=220)

                e1 = Entry(window)
                e1.place(x=10, y=240)
                e1.bind('<Return>', get_value)  #To get the value entered in the entry when Return is pressed.
                print("Past bind1")
                print(self.entry)
                print("Past bind2")
                break

            except ValueError as e :
                print("\n\tPlease Enter only Numbers!!")


obj1    = hangman()
label2  = Label(window, text="Start")
bt      = Button(window, text="Play", command=lambda: obj1.clicked(label2))

bt.place(x=150, y=125)

window.mainloop()

我希望能够捕获到异常,并打印我的消息,而不是标准异常错误。

1 个答案:

答案 0 :(得分:2)

如果在get_value函数中放置try / except块,则可以正确捕获异常:

from tkinter import *
window = Tk()
window.geometry('400x400')


class hangman:
    def __init__(self):
        self.entry = ''

    def clicked(self, label2):
        label2.place(x=100, y=200)

        while True:
            def get_value(event):
                try:
                    self.entry = e1.get()
                    self.entry = int(self.entry)
                    print(self.entry)
                except ValueError as e:
                    print("\n\tPlease Enter only Numbers!!")

            Label(window, text="Enter any number :").place(x=10, y=220)

            e1 = Entry(window)
            e1.place(x=10, y=240)
            e1.bind('<Return>', get_value)  # To get the value entered in the entry when Return is pressed.
            print("Past bind1")
            print(self.entry)
            print("Past bind2")
            break


obj1 = hangman()
label2 = Label(window, text="Start")
bt = Button(window, text="Play", command=lambda: obj1.clicked(label2))

bt.place(x=150, y=125)

window.mainloop()