Gtk4 Spreadsheet Sgskip

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to embed Matplotlib in a Gtk4 application and interact with a treeview to store data. You will be able to plot data by double-clicking on an entry in the treeview.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/custom_backends("`Custom Backends`") matplotlib/AdvancedTopicsGroup -.-> matplotlib/event_handling("`Event Handling`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/keyword_arguments -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} matplotlib/figures_axes -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} matplotlib/line_plots -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} matplotlib/custom_backends -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} matplotlib/event_handling -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/variables_data_types -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/numeric_types -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/strings -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/booleans -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/type_conversion -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/for_loops -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/lists -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/tuples -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/dictionaries -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/function_definition -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/importing_modules -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/using_packages -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/standard_libraries -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/classes_objects -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/constructor -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/polymorphism -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/encapsulation -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/math_random -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/data_collections -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/numerical_computing -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/data_visualization -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} python/build_in_functions -.-> lab-48761{{"`Gtk4 Spreadsheet Sgskip`"}} end

Set up the Environment

First, you need to create a virtual environment and install the necessary packages.

## create virtual environment
python3 -m venv matplotlib_tutorial

## activate the environment
source matplotlib_tutorial/bin/activate

## install necessary packages
pip install numpy matplotlib PyGObject

Create the Application Window

Next, you need to create the application window that will contain the treeview and the Matplotlib plot.

import gi

gi.require_version('Gtk', '4.0')
from gi.repository import Gtk

from numpy.random import random

from matplotlib.backends.backend_gtk4agg import FigureCanvas
from matplotlib.figure import Figure


class DataManager(Gtk.ApplicationWindow):
    num_rows, num_cols = 20, 10

    data = random((num_rows, num_cols))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_default_size(600, 600)

        self.set_title('GtkListStore demo')

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, homogeneous=False,
                       spacing=8)
        self.set_child(vbox)

        label = Gtk.Label(label='Double click a row to plot the data')
        vbox.append(label)

        sw = Gtk.ScrolledWindow()
        sw.set_has_frame(True)
        sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        sw.set_hexpand(True)
        sw.set_vexpand(True)
        vbox.append(sw)

        model = self.create_model()
        self.treeview = Gtk.TreeView(model=model)
        self.treeview.connect('row-activated', self.plot_row)
        sw.set_child(self.treeview)

        fig = Figure(figsize=(6, 4), layout='constrained')

        self.canvas = FigureCanvas(fig)
        self.canvas.set_hexpand(True)
        self.canvas.set_vexpand(True)
        vbox.append(self.canvas)
        ax = fig.add_subplot()
        self.line, = ax.plot(self.data[0, :], 'go')

        self.add_columns()

    def plot_row(self, treeview, path, view_column):
        ind, = path
        points = self.data[ind, :]
        self.line.set_ydata(points)
        self.canvas.draw()

    def add_columns(self):
        for i in range(self.num_cols):
            column = Gtk.TreeViewColumn(str(i), Gtk.CellRendererText(), text=i)
            self.treeview.append_column(column)

    def create_model(self):
        types = [float] * self.num_cols
        store = Gtk.ListStore(*types)
        for row in self.data:
            it = store.insert(-1)
            store.set(it, {i: val for i, val in enumerate(row)})
        return store


def on_activate(app):
    manager = DataManager(application=app)
    manager.show()


app = Gtk.Application(application_id='org.matplotlib.examples.GTK4Spreadsheet')
app.connect('activate', on_activate)
app.run()

Plot the Data

Now, you will plot the data by double-clicking on an entry in the treeview.

    def plot_row(self, treeview, path, view_column):
        ind, = path
        points = self.data[ind, :]
        self.line.set_ydata(points)
        self.canvas.draw()

Add Columns to the Treeview

You need to add columns to the treeview to display the data.

    def add_columns(self):
        for i in range(self.num_cols):
            column = Gtk.TreeViewColumn(str(i), Gtk.CellRendererText(), text=i)
            self.treeview.append_column(column)

Create the Model

Finally, you need to create the model to store the data.

    def create_model(self):
        types = [float] * self.num_cols
        store = Gtk.ListStore(*types)
        for row in self.data:
            it = store.insert(-1)
            store.set(it, {i: val for i, val in enumerate(row)})
        return store

Summary

In this lab, you learned how to embed Matplotlib in a Gtk4 application and interact with a treeview to store data. You can now plot data by double-clicking on an entry in the treeview.

Other Python Tutorials you may like