Thonny on the Raspberry Pi with Python code and a tkinter window showing the CPU temperature 46.9 degrees in green

Raspberry Pi Programming with Python: Getting Started with Thonny

You have a Raspberry Pi and want to learn programming with it? Then you don’t need to install anything: Python and the beginner-friendly editor Thonny already come with Raspberry Pi OS with desktop. In this guide we show you how to get started with Raspberry Pi programming in Python: you open Thonny, write a first program that reads the CPU temperature, and turn it into your own window with a live display. We also cover how to install extra packages without running into the error externally-managed-environment. Neither example needs any additional hardware.

What you need

Links marked with * are affiliate links, which makes them advertising. If you buy through one, I earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. Learn more

If your Pi runs headless with Raspberry Pi OS Lite, Thonny and the desktop are missing. Python is still there: you write programs over SSH with the nano editor and start them with python3 file.py. For getting started, we recommend the desktop version. Our Raspberry Pi Imager guide shows how to get Raspberry Pi OS onto the SD card. The screenshots in this article were taken on a Raspberry Pi 5 with the current Raspberry Pi OS (as of October 2026).

Which programming language for the Raspberry Pi?

Our recommendation for beginners is Python. The language is preinstalled on the Pi, reads almost like English, and practically every guide for sensors, cameras and GPIO pins uses Python. The alternatives have their place, but for different goals:

LanguageSuited forOn the Pi
Pythonbeginners and almost every Pi projectpreinstalled, the Thonny editor as well
Scratchkids, programming with blocks instead of textinstall via “Recommended Software”
MicroPythonthe Raspberry Pi Pico microcontrollerruns on the Pico, not on the Pi itself
C/C++time-critical programs, existing C librariescompiler included, unnecessarily hard for beginners

Scratch is not included in the current Raspberry Pi OS. You find it in the start menu under Preferences → Recommended Software in the “Programming” section: tick “Scratch 3” and click “Apply”.

Recommended Software window on the Raspberry Pi with the Programming section, Scratch 3 unticked and Thonny ticked
Scratch 3 can be installed from Recommended Software, Thonny is already ticked

If you want to program a Raspberry Pi Pico later, our Pico getting started guide with MicroPython will help. What you learn about Python here applies there almost unchanged.

Python is already installed

You don’t need to install Python on the Raspberry Pi. A command in the terminal (the black icon at the top of the taskbar) shows which version you have:

python3 --version

On our Pi, the current Raspberry Pi OS reports Python 3.13.5. Get used to always typing python3. Older guides sometimes still mention Python 2, which no longer exists on the current Raspberry Pi OS, and you don’t need it either.

Start and set up the Thonny Python editor

Thonny is the Python editor for beginners on the Raspberry Pi: editor, run button and a Python console in a single window. You start it from the raspberry icon at the top left under Programming → Thonny. Next to it you’ll find Geany, an editor for more advanced users that you can ignore for now.

Raspberry Pi OS start menu with the Programming submenu open, showing Geany Programmer's Editor and Thonny
You find Thonny in the start menu under Programming

Simple and regular mode

On first launch, Thonny opens in simple mode with large buttons and no menu bar. That’s enough for trying things out. For this guide, however, you’ll need the settings later, so switch right away: click Switch to regular mode at the top right, close Thonny and start it again. You now have the menu bar with File, Edit, View, Run and Tools at the top.

Thonny in simple mode with large New, Load, Save, Run, Debug and Stop buttons and the Switch to regular mode link at the top right
Thonny starts in simple mode, the link at the top right switches to regular mode

In regular mode the toolbar buttons have no labels. The most important ones: New (green plus) creates a new file, Run (green arrow or F5) starts your program, Stop (red button) ends it. You write code in the editor at the top, and output and error messages appear in the shell at the bottom. You can also try out individual Python commands directly in the shell.

Your first program

Type this single line into the editor:

print("Hello Raspberry Pi")

Click Run. Thonny first asks where to save the file. Create a new folder meinprojekt (or any name you like, just use it consistently below) in your home folder and save the file there as hello.py. The shell then shows “Hello Raspberry Pi”. print() outputs whatever is inside the parentheses, text goes in quotes.

Example 1: Read the CPU temperature

The first real program reads the processor temperature every two seconds. You don’t need any hardware for it, the gpiozero library is preinstalled on Raspberry Pi OS. Create a new file with New, paste the code and save it as cpu_temperature.py:

from time import sleep
from gpiozero import CPUTemperature

cpu = CPUTemperature()

while True:
    temperature = cpu.temperature
    print(f"CPU temperature: {temperature:.1f} °C")
    sleep(2)

After clicking Run, a new line with the current temperature appears in the shell every two seconds.

Thonny with cpu_temperature.py in the editor and three CPU temperature lines between 48.5 and 49 degrees in the shell
The program prints the CPU temperature to the shell every two seconds

What the lines mean

  • from … import … pulls ready-made building blocks into your program: sleep for waiting and CPUTemperature for reading the temperature sensor inside the processor. The gpiozero documentation lists everything else the library offers.
  • cpu = CPUTemperature() creates an object and stores it in the variable cpu. A variable is a name for a value you need again later.
  • while True: starts an endless loop. Python repeats everything indented below it until you stop the program. Indentation is mandatory in Python, and four spaces is the convention. Thonny adds it automatically after the colon.
  • f"… {temperature:.1f} °C" is an f-string: the value in curly braces is inserted into the text, :.1f rounds it to one decimal place.

Stopping the program

Because the loop runs forever, you end the program with the red Stop button. Thonny then restarts Python, and the shell shows the line with the Python version again. In the terminal, you stop a program with Ctrl+C. Python then reports KeyboardInterrupt. That’s not a bug in your code, it’s Python’s way of saying the program was stopped from outside.

Write the readings to a file

Output in the shell is gone once you close it. This variant additionally writes each reading with date and time to a CSV file that you can later open in a spreadsheet, for example LibreOffice Calc. It isn’t preinstalled on the regular desktop version, you’ll find it in Recommended Software in the “Office” section. Create another file with New and save it as cpu_temperature_log.py, the first program stays unchanged:

import csv
from datetime import datetime
from time import sleep
from gpiozero import CPUTemperature

cpu = CPUTemperature()

# "a" appends to the file, so old measurements are kept
with open("cpu_temperature.csv", "a", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    while True:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        temperature = round(cpu.temperature, 1)
        writer.writerow([now, temperature])
        file.flush()  # write to the file right away
        print(now, temperature)
        sleep(2)

Two things are new: with open(…) opens the file and closes it cleanly as soon as the program ends, and file.flush() makes sure each value is written to the file immediately rather than only on exit. The file cpu_temperature.csv ends up in the same folder as the program.

Thonny with cpu_temperature_log.py and four lines of date, time and temperature in the shell
The log variant prints every reading with a timestamp and writes it to a CSV file

Step by step with the debugger

When a program doesn’t do what it should, the debugger helps. Start cpu_temperature.py with the Debug button (the icon to the right of the green arrow) instead of Run. Thonny then doesn’t run the program in one go but waits for you. With Step over (F6 or the first of the three line icons next to it) you execute one line after another, the current line is highlighted in yellow. Under View → Variables you can see which value each variable currently holds.

Thonny in debug mode with the print line highlighted in yellow and the Variables pane showing temperature with the value 47.95
In the debugger Thonny shows the unrounded value 47.95, the output rounds it to 48.0

In the screenshot, temperature is 47.95, the output later shows 48.0. That’s exactly what :.1f does: the stored value stays unchanged, only the display is rounded.

Example 2: Your own window with tkinter

Text in the shell is handy, but your own window looks like a real program. Python includes the tkinter library for this, and it’s also preinstalled on Raspberry Pi OS. The following program shows the CPU temperature in large digits in a window, updates it every two seconds and turns it red from 60 °C. Save it as cpu_temperature_window.py:

import tkinter as tk
from gpiozero import CPUTemperature

cpu = CPUTemperature()

window = tk.Tk()
window.title("CPU temperature")

label = tk.Label(window, font=("Arial", 48), padx=40, pady=20)
label.pack()


def update():
    temperature = cpu.temperature
    label.config(text=f"{temperature:.1f} °C")
    # red above 60 °C, green below
    label.config(fg="red" if temperature > 60 else "green")
    window.after(2000, update)  # run again in 2 seconds


update()
window.mainloop()
Small CPU temperature window showing 46.9 degrees Celsius in green in front of the Thonny editor
The tkinter window shows the CPU temperature live, in green below 60 °C

Three things are new:

  • tk.Tk() creates the window, tk.Label a text field inside it, and label.pack() places the text field in the window.
  • def update(): defines your own function, a named block of code you can call as often as you like. It reads the temperature, writes it to the text field and picks the color with if … else.
  • Instead of while True and sleep, tkinter uses window.after(2000, update): the window calls the function again by itself after 2000 milliseconds. An endless loop with sleep would freeze the window, because tkinter would never get the chance to redraw it. window.mainloop() keeps the window open until you close it.

To test the red display, lower the 60 in the code to 40. If your Pi regularly ends up in the red zone in everyday use, take a look at our article on Raspberry Pi fan control.

Installing extra packages: the “externally-managed-environment” error

Sooner or later you’ll need a library that isn’t preinstalled. Many guides recommend pip install for that. On the current Raspberry Pi OS, however, the command stops with an error message:

Raspberry Pi terminal with the command pip install requests and the error message error externally-managed-environment
pip refuses the system-wide installation and itself suggests apt or a virtual environment

The reason: Raspberry Pi OS manages its Python packages itself through the apt package manager. To keep pip from overwriting them and breaking the system, Python blocks the installation. The message already names both solutions, and that’s exactly the order you should follow. The official documentation on Python on the Raspberry Pi, which the link in the error message leads to, describes both approaches as well.

Option 1: Install the package via apt

Many well-known libraries are available as ready-made packages with the prefix python3-. For the pyfiglet library, which prints text in large ASCII letters, it looks like this:

sudo apt update
sudo apt install python3-pyfiglet

apt search python3-NAME tells you whether a package exists. Packages from apt get their updates with the normal system update, more on that in our guide Update Raspberry Pi OS.

Option 2: Virtual environment with access to the system packages

If there’s no apt package, as with the cowsay library (apt search python3-cowsay finds nothing), you create a virtual environment, venv for short. It’s a separate folder with its own Python installation in which pip is allowed. The important part is the flag --system-site-packages: without it, the venv no longer sees the preinstalled libraries such as gpiozero or picamera2, and your programs fail on import.

python3 -m venv --system-site-packages ~/meinprojekt
source ~/meinprojekt/bin/activate
pip install cowsay

The first line creates the venv in the meinprojekt folder you already use for your programs. Your .py files stay where they are, only the venv’s own files are added (the folders bin, include, lib and lib64, plus pyvenv.cfg and .gitignore). The second line activates it in the terminal, recognizable by (meinprojekt) in front of the prompt, and the third installs the package. You can check that everything works with:

python -c "import gpiozero, cowsay; print('ok')"

If the terminal then shows ok, both the system library gpiozero and the new package are available.

Using option 2 in Thonny: switch the interpreter

Once you’ve created the venv from option 2, Thonny needs to know about it. To have Thonny run your programs with the venv, open Tools → Options… in regular mode and switch to the Interpreter tab. Leave “Local Python 3” selected at the top and enter the path /home/pi/meinprojekt/bin/python under “Python executable”, or pick it with the button with the three dots. If your user isn’t called pi, replace the name in the path. To see the exact path, run echo ~/meinprojekt/bin/python in the terminal. After clicking OK, the shell restarts and shows the new path, which also appears in the status bar at the bottom right.

Thonny options on the Interpreter tab with Local Python 3 and the Python executable /home/pi/meinprojekt/bin/python
On the Interpreter tab you point Thonny to the Python of the virtual environment
Careful with “New virtual environment” in Thonny

In the same dialog, Thonny offers a “New virtual environment” link. The venv it creates has no access to the system packages: in our test, even import gpiozero failed with ModuleNotFoundError. So create the venv in the terminal as shown above and only point Thonny to it.

We advise against the --break-system-packages flag that the error message also mentions. It installs the package system-wide anyway and can lead to broken dependencies with the next system update.

Starting programs automatically

So far, your programs only run while Thonny is open. In the terminal, switch to the folder with cd ~/meinprojekt and start a program with python3 cpu_temperature.py, with the venv via ~/meinprojekt/bin/python cpu_temperature.py. If a program should start by itself after every reboot, our guide on autostart for scripts shows the right options. For tasks at fixed intervals, such as one reading per hour, a cron job is the better choice.

Where to go next

With Thonny, variables, loops, functions and packages you have the toolkit for most Pi projects. These guides build directly on it:

For hardware experiments, a component set like the Freenove Starter Kit* with breadboard, LEDs and sensors is a good next step. And once Thonny feels too simple: Geany is already installed, and you’ll find Visual Studio Code in Recommended Software.

Frequently asked questions about programming the Raspberry Pi with Python

Which Python version does Raspberry Pi OS have?

The current Raspberry Pi OS ships with Python 3.13 (as of October 2026, 3.13.5 on our Pi). The command python3 --version in the terminal shows the exact version.

Do I need to install Python on the Raspberry Pi?

No. Python 3 is preinstalled on Raspberry Pi OS, and the desktop version also includes the Thonny editor and libraries such as gpiozero and tkinter. You install additional libraries via apt or with pip in a virtual environment.

Do I need Python 2?

No. Python 2 has not been maintained since 2020 and is no longer included in the current Raspberry Pi OS. Old Python 2 scripts need to be ported to Python 3, which mostly affects print statements without parentheses.

Can I program on the Raspberry Pi without a monitor?

Yes. Over SSH you write programs in the terminal, for example with the nano editor, and run them with python3 file.py. Thonny and tkinter windows need the desktop, though, so a monitor is more convenient for getting started.

Why does pip install report externally-managed-environment?

Raspberry Pi OS manages its Python packages through apt and protects them from pip. Install the package with sudo apt install python3-NAME instead, or create a virtual environment with python3 -m venv --system-site-packages and use pip inside it.

Is Scratch preinstalled on the Raspberry Pi?

Not on the current Raspberry Pi OS. You install Scratch 3 via Preferences → Recommended Software in the Programming section.

Conclusion

You don’t need to install anything to start programming on the Raspberry Pi: open Thonny, create a file, click Run. With the two examples you’ve already used variables, loops, functions, files and your own window. If you need extra packages, try apt first and otherwise a venv with --system-site-packages. The next step worth taking is the GPIO pins, and then your first LED lights up. Have fun programming!

Similar Posts