This is a quick crash course on how to set up, use, and change virtual environments in Thonny on a Raspberry Pi.
In late 2023 Bookworm OS for the Raspberry Pi rolled out and this new OS restricted the ability to install externally managed packages system-wide with pip. This now means that many of these packages will need to be installed in a virtual environment - which as the name implies, is an isolated virtual environment where we can do what we want without affecting the rest of our system.
Unfortunately, these changes have affected the way we use packages in Thonny, meaning that you may have encountered this issue when trying to install a package:
Thankfully, the Thonny folks have made it incredibly easy to use virtual environments in Thonny. To start we will navigate to the interpreter options which you can access by clicking run > configure interpreter.
In this window, we can then create and select our virtual environments. If you have previously made a virtual environment, you will be able to find it under the Python executable window, if you have not, you can create one in the bottom right.
After creating a new environment, you will be prompted to select an empty folder, and this is where your virtual environment will be located. Almost anywhere will do but creating a new folder in your home directory provides an easy place to access it. You can achieve this by clicking on Home on the left side, then selecting the new folder icon at the top (calling it whatever you want) and hitting Create.
Once you create the folder, this window will automatically open that folder (which should be empty). After this, simply click OK, and the new virtual environment will be generated.
Once it has finished, you should be returned to the configure interpreter window and the path that you created should be selected under the Python executable drop-down menu (the name of the new folder you made should be in the path). Hit OK in that window and you are done!
And that's it, you have now set up the virtual environment and should be able to install your packages through the package manager as usual.
Now every time you open Thonny, it should open with the same configuration as last time, meaning it will keep using this virtual environment that you have set up until you change out of it. If you wish to create a new virtual environment, you can do so by repeating the same steps as above. If you wish to swap virtual environments, you can do so by selecting it in the Python executable drop-down menu in the interpreter window.