从python中的包导入Error类

问题描述 投票:1回答:1

如何在python中导入Error类(并且只有错误类,而不是命名空间)才能在异常处理中使用?

什么不打算使用:

from tkinter import _tkinter as tk

try:
    ...
except tk.TclError:
    print('Oops. Bad window path.')

我已经尝试了上面的方法,但是这样做也可以将一些其他东西导入到我不需要的命名空间中,我还需要使用tk.TclError来引用它而不是简单的TclError。

我试图避免,因为它导入了我不需要的整个包,我只需要处理异常:

import tkinter as tk

try:
    ...
except tk.TclError:
    print('Oops. Bad window path.')

那么如何从包中单独导入Error类,而不是获取整个tkinter命名空间,如果这甚至是可能的或可推荐的?

我有两个单独的程序,我会在这里称它们为A和B来缩短它。

我想要实现的目标

A.朋友

## Communicator ##
import B

#... Some irrelevant code ...
GUI = B.start()

try:
    #Tell the GUI to modify something, for example:
    GUI.entry.insert(0, 'Input')
except TclError:
    #Modification failed due to Bad Window Path

B.朋友

## GUI ##
import tkinter as tk

#Little Function to give the Communicator the required object to start/handle the GUI
def start():
    root = tk.Tk()
    run = Alarmviewer(root)
    return run

#... GUI initialization, creating/destroying of windows, modifications, etc
python-3.x exception tkinter
1个回答
1
投票

TclError类可以从tkinter导入。要使它成为tk.TclError只需导入名为tkintertk

import tkinter as tk
try:
    ...
except tk.TclError:
    ...

当然,如果你愿意的话,你可以导入TclError异常,尽管在这个特定的例子中导入整个模块真的是doesn't have any actual advantage

from tkinter import TclError
try:
    ...
except TclError:
    ...

您的问题声称您必须将其引用为tk.TclError,但这是一个错误的陈述。您可以通过将其导入的名称来引用它。名称无关紧要,重要的是实际的异常对象本身。

例如,创建一个名为gui.py的文件,并在该文件中放置:

# gui.py
import tkinter as tk
def do_something():
    raise tk.TclError("something bad happened")

接下来,在另一个文件中添加以下代码:

from tkinter import TclError
import gui

try:
    gui.do_something()
except TclError:
    print("I caught the TclError")

当您运行代码时,您应该看到“我抓住了TclError”。

© www.soinside.com 2019 - 2024. All rights reserved.