1

抽象的问题

如何最好地导入在 tkinter 程序运行期间可能会或可能不会成功导入的包,比如按下按钮。

目前我正在使用:

def ButtonFunction(self):

    try:
         import package
    except Exception as e: 
         print(e)  # I don't want the execution to stop if this cannot be imported. 

这是最好的方法吗?在函数调用中导入包有什么问题吗?

具体问题

我正在使用 CiruitPython 与 MCP2221 板进行通信,但导入仅在板已连接时才有效。如果板子没有连接,我希望程序仍然可以工作,并希望用户在程序启动后连接板子。

具体代码:

def _init_hardware(self):
        try:    
            # Set an Environment Variable so Adafruit Blinka knows we're using the MCP2221
            os.environ["BLINKA_MCP2221"] = "1"
            import board
            import busio
        except:
            raise RuntimeError('Could not initialise Circuit Python. Check hardware is plugged in.')

具体来说boardbusio如果没有检测到板,则不会导入,因此我已将此代码从所有其他导入所在的位置移至初始化所有硬件的函数。

4

0 回答 0