Написание цикла / исключения для JSONDecodeError - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь создать программу, которая будет печатать JSON результатов в Tkinter GUI, но я столкнулся с вопросом: что, если публикуемое изображение достаточно четкое, чтобы получить результат?

Я знаю, что могу использовать if, иначе l oop или исключение, но я не смог получить желаемый результат GUI, который сообщает пользователю, что в случае ошибки возникает ошибка.

Ошибка, которую я получаю в терминале:

File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

И мой код до сих пор:

if: json.decoder.JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(oops.winfo_screenwidth()/2 - window_width/2)
    position_down = int(oops.winfo_screenheight()/2 - window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops, your Photo could not be analyzed!', font='Verdana 70 bold').pack()
    oops.after(5000, oops.destroy)

else:
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)

Я пытался попробовать, кроме исключения например, также без получения желаемого результата:

try:
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
except json.JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(oops.winfo_screenwidth()/2 - window_width/2)
    position_down = int(oops.winfo_screenheight()/2 - window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops, your Photo could not be nalyzed!', font='Verdana 70 bold').pack()

Любая помощь будет оценена, спасибо!

1 Ответ

0 голосов
/ 18 февраля 2020

Этот код решил мою проблему: мне нужно было добавить исключение позже в моем скрипте, а также при печати результатов.

Кроме того, я по глупости забыл добавить mainloop строку

try:
    global name
    name = date_time + "_result.json"
    file = open(name, 'wb')
    global data
    data = response.content
    write = file.write(data)
    pretty_json = json.loads(data)
    print(pretty_json)
except JSONDecodeError:
    oops = tk.Tk()
    window_width = oops.winfo_reqwidth()
    window_height = oops.winfo_reqheight()
    # Gets both half the screen width/height and window width/height
    position_right = int(window_width/2)
    position_down = int(window_height/2)
    # Positions the window in the center of the page.
    oops.geometry("+{}+{}".format(position_right, position_down))
    main = tk.Label(oops, text='Oops!', font='Verdana 80 bold').pack()
    detail = tk.Label(oops, text='Your Photo could not be analyzed', font='Verdana 60').pack()
    oops.after(5000, oops.destroy)
    oops.mainloop()
...