The abstract problem
How to best import a package that may or may not import successfully during the run of a tkinter program, say on a button press.
At the moment I am using:
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.
Is this the best way to go about it? Is there any issue with importing packages within a function call?
The specific problem
I'm using CiruitPython to communicate with an MCP2221 board but the import only works if the board is connected. I want the program to still work if the board is not connected and a way for the user to connect the board after the program has started.
The specific code:
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.')
Specifically board and busio will not import if there is no board detected so I have moved this code from where all the other imports are to the function which initialises all the hardware.