How To Create Modern GUI In Python | Python Eel Tutorial

All About Python
8 Feb 202323:36

Summary

TLDRDans cette vidéo, Vishesh Dvivedi nous guide à travers la création d'une interface utilisateur graphique moderne en Python en utilisant la bibliothèque 'eel'. Il commence par expliquer ce qu'est eel, comment il fonctionne, et comment il permet de mélanger HTML, CSS et JavaScript avec Python pour développer des applications de bureau attrayantes. Le tutoriel couvre l'installation de eel, la configuration de l'environnement de développement, et la création d'une application de liste de tâches (todo list) pas à pas. Enfin, Vishesh démontre l'application finale en action, offrant des conseils et des astuces tout au long du chemin.

Takeaways

  • 🐍 La bibliothèque 'eel' permet de créer des interfaces utilisateur graphiques modernes en Python, en utilisant HTML et CSS pour le design.
  • 🎨 HTML et CSS offrent des capacités étendues pour créer des interfaces utilisateur attrayantes, surpassant d'autres frameworks ou technologies.
  • 🔧 'eel' fonctionne de manière similaire à Electron JS, en exécutant un serveur web local qui expose des fonctions Python au code JavaScript et vice versa.
  • 💻 Les développeurs peuvent facilement intégrer l'interface utilisateur en HTML/CSS avec les fonctionnalités de l'application écrites en Python, en utilisant JavaScript pour appeler des fonctions Python.
  • 🛠️ Pour démarrer avec 'eel', il suffit d'installer le module via pip avec la commande 'pip install eel'.
  • 📁 La structure du projet comprend un fichier 'main.py' pour le code Python, et un dossier 'web' contenant les fichiers HTML, CSS, et JS.
  • 🎲 Bootstrap et jQuery peuvent être utilisés pour améliorer l'interface utilisateur avec des designs attractifs et des animations.
  • ⚙️ Le développement avec 'eel' implique l'utilisation de décorateurs '@eel.expose' pour rendre les fonctions Python accessibles au JavaScript.
  • 📊 Un exemple d'application de liste de tâches (todo list) démontre comment intégrer des fonctionnalités comme la création, l'affichage, et la suppression de tâches.
  • 🔄 Les données de l'application peuvent être stockées dans un fichier JSON, facilitant la persistance des données entre les sessions d'application.

Q & A

  • Qu'est-ce que la bibliothèque Eel en Python ?

    -Eel est une bibliothèque simple pour Python, similaire à Electron JS, qui permet de créer des interfaces utilisateur graphiques modernes en utilisant HTML et CSS. Elle fonctionne en exécutant un serveur web local qui expose des fonctions Python au code JavaScript et vice versa.

  • Pourquoi utiliser HTML et CSS pour créer des GUI en Python ?

    -HTML et CSS offrent d'énormes capacités aux concepteurs pour utiliser leur imagination et créer des interfaces utilisateur attrayantes. Aucun autre framework, technologie ou langage ne peut égaler HTML et CSS dans ses capacités pour la création de GUI.

  • Comment installer la bibliothèque Eel pour Python ?

    -Pour installer Eel, il suffit d'ouvrir le terminal de votre système ou de VSCode et de taper la commande `pip install eel`. Cette commande téléchargera et installera le module Eel dans votre système.

  • Quels fichiers sont nécessaires pour créer une application de bureau avec Eel ?

    -Pour créer une application avec Eel, vous avez besoin d'un fichier `main.py` pour le code Python, d'un dossier `web` contenant les fichiers HTML, CSS et JavaScript pour l'interface utilisateur, et de fichiers supplémentaires comme Bootstrap et jQuery pour améliorer l'UI.

  • Comment démarrer l'application de bureau avec Eel ?

    -Après avoir initialisé Eel avec le dossier contenant les fichiers web via `eel.init('web')`, vous démarrez l'application avec `eel.start('index.html')`, qui ouvre une fenêtre de navigateur Chrome pour afficher l'interface utilisateur.

  • Comment Eel permet-il l'interaction entre le code Python et JavaScript ?

    -Eel expose des fonctions Python au code JavaScript (et vice versa) en utilisant des décorateurs et des appels de fonction spéciaux, permettant ainsi aux développeurs de créer des fonctionnalités complexes et interactives entre le backend Python et le frontend HTML/CSS/JavaScript.

  • Quel est le rôle du fichier `eel.js` dans un projet Eel ?

    -Le fichier `eel.js` est généré automatiquement par Eel et doit être inclus dans le fichier HTML. Il est essentiel pour permettre l'appel de fonctions Python depuis le code JavaScript et vice versa, facilitant ainsi l'interaction entre le frontend et le backend.

  • Comment les données sont-elles gérées dans l'application de tâches à faire avec Eel ?

    -Les données des tâches à faire sont stockées dans un fichier JSON. Des fonctions Python sont utilisées pour lire, écrire, ajouter et supprimer des données dans ce fichier, permettant une persistance des données entre les sessions de l'application.

  • Comment peut-on appeler une fonction Python depuis JavaScript dans Eel ?

    -Pour appeler une fonction Python depuis JavaScript, utilisez la syntaxe `eel.nom_de_la_fonction_python(arguments)(fonction_de_rappel_js)`. Cela permet d'exécuter des fonctions Python et de gérer les résultats dans le code JavaScript.

  • Peut-on utiliser Eel pour des applications de production ?

    -Eel est principalement destiné à la création rapide de prototypes et d'applications de bureau légères avec des interfaces utilisateur modernes. Pour des applications de production complexes, d'autres solutions peuvent être plus appropriées en fonction des exigences de performance et de sécurité.

Outlines

00:00

😀 Introduction à Eel pour les interfaces graphiques modernes

Dans cette introduction, Vishesh Dvivedi présente son tutoriel sur la création d'interfaces utilisateur graphiques modernes en Python en utilisant la bibliothèque 'eel'. Il explique que Eel permet aux développeurs de créer des applications de bureau attrayantes en combinant HTML, CSS et JavaScript pour le design de l'interface, avec Python pour les fonctionnalités principales. Eel fonctionne en exécutant un serveur web local qui facilite la communication entre le code JavaScript et Python, permettant ainsi une grande flexibilité et créativité dans le développement des applications. Vishesh annonce qu'il guidera les téléspectateurs à travers la création d'une application de liste de tâches à faire pour illustrer l'utilisation d'Eel.

05:02

🚀 Configuration initiale et démarrage avec Eel

Dans cette section, Vishesh guide les téléspectateurs à travers les étapes initiales pour commencer à travailler avec Eel, en commençant par l'installation du module via pip. Il montre ensuite comment structurer le projet en créant un fichier 'main.py' pour le code Python, un dossier 'web' pour les fichiers HTML, CSS, et JavaScript, et introduit l'utilisation de Bootstrap et jQuery pour améliorer l'interface utilisateur. Vishesh explique comment initialiser le serveur web local d'Eel et ouvrir l'application dans une fenêtre de navigateur, démontrant ainsi la facilité avec laquelle on peut démarrer le développement d'une application de bureau avec une interface utilisateur moderne en Python.

10:02

📝 Création de fonctionnalités Todo avec Eel

Vishesh entre dans le vif du sujet en montrant comment ajouter des fonctionnalités à l'application de liste de tâches à faire. Il commence par détailler la création de fonctions Python pour lire et écrire des données dans un fichier JSON, qui sert de base de données locale pour les tâches à faire. Il utilise le décorateur '@eel.expose' pour rendre ces fonctions accessibles depuis le code JavaScript, permettant ainsi une interaction fluide entre l'interface utilisateur et la logique de l'application. Vishesh illustre la création, l'affichage, et la suppression des tâches à faire, soulignant la puissance de Eel pour développer des applications de bureau interactives.

15:03

🌐 Intégration de l'interface utilisateur et fonctionnalités JavaScript

Cette partie se concentre sur le développement de l'interface utilisateur et l'intégration des fonctionnalités JavaScript avec le backend Python. Vishesh explique comment utiliser les fonctions exposées par Python pour interagir avec l'application depuis l'interface utilisateur. Il montre comment créer des éléments de l'interface utilisateur dynamiquement en utilisant JavaScript pour afficher les tâches à faire et gérer les interactions de l'utilisateur, comme l'ajout et la suppression de tâches. Cette section démontre l'efficacité de Eel pour lier le frontend et le backend d'une application, permettant une expérience utilisateur riche et réactive.

20:10

🎉 Conclusion et ressources

Pour conclure, Vishesh récapitule les points clés du tutoriel, encourageant les téléspectateurs à expérimenter avec Eel pour créer leurs propres applications de bureau avec interfaces graphiques modernes. Il invite à liker la vidéo, à s'abonner à la chaîne pour plus de tutoriels, et à partager des problèmes ou des questions dans les commentaires. Vishesh assure que les ressources utilisées dans le tutoriel sont disponibles dans la description de la vidéo, facilitant ainsi pour les téléspectateurs le suivi et l'application des concepts présentés.

Mindmap

Keywords

💡eel

Eel est une bibliothèque Python simple conçue pour créer des interfaces utilisateur graphiques modernes en utilisant HTML et CSS, similaire à Electron JS. Elle permet d'exposer des fonctions Python au code JavaScript et vice-versa, en exécutant un serveur web local lors du démarrage de l'application Python. Dans le script, Eel est utilisé pour intégrer des fonctionnalités de base de l'application écrites en Python avec une interface utilisateur créée en HTML/CSS, facilitant ainsi le développement d'applications de bureau attrayantes.

💡interface utilisateur graphique (GUI)

L'interface utilisateur graphique (GUI) fait référence à l'interface visuelle d'une application qui permet une interaction entre l'utilisateur et l'application via des éléments graphiques tels que des boutons, des formulaires et d'autres contrôles, au lieu de commandes textuelles. Le script met en évidence l'utilisation de HTML et CSS, assistés par la bibliothèque Eel, pour créer une GUI attrayante pour une application de bureau Python, démontrant la puissance et la flexibilité de ces technologies dans la conception d'interfaces utilisateur.

💡HTML

HTML, qui signifie HyperText Markup Language, est le langage de balisage standard pour créer des pages web. Il structure le contenu de la page web et est essentiel pour développer l'interface utilisateur des applications web. Dans le contexte de la vidéo, HTML est utilisé pour structurer l'interface utilisateur de l'application de bureau, démontrant comment les développeurs Python peuvent utiliser des compétences web pour améliorer l'esthétique et la fonctionnalité de leurs applications.

💡CSS

CSS, ou Cascading Style Sheets, est un langage de feuille de style utilisé pour décrire la présentation d'un document écrit en HTML. CSS définit comment les éléments HTML doivent être affichés à l'écran. Dans la vidéo, CSS est utilisé conjointement avec HTML pour styliser l'interface utilisateur de l'application de bureau, illustrant la capacité de CSS à transformer des structures HTML simples en interfaces riches et visuellement attrayantes.

💡JavaScript

JavaScript est un langage de programmation dynamique qui, dans le contexte du web, est principalement utilisé pour créer des interactions dynamiques sur les pages web. Dans la vidéo, JavaScript est utilisé pour manipuler l'interface utilisateur HTML/CSS de l'application de bureau et pour faciliter la communication entre le code Python backend et le frontend HTML/CSS, grâce à l'intégration offerte par Eel.

💡pip

Pip est un système de gestion de paquets utilisé pour installer et gérer des logiciels écrits en Python. Dans la vidéo, la commande `pip install eel` est utilisée pour télécharger et installer la bibliothèque Eel, ce qui est le premier pas pour permettre le développement de l'application de bureau avec une interface utilisateur moderne.

💡Visual Studio Code (VSCode)

Visual Studio Code (VSCode) est un éditeur de code source gratuit et puissant développé par Microsoft. Il prend en charge une variété de langages de programmation, y compris Python. Dans le script, VSCode est l'environnement de développement utilisé pour écrire et exécuter le code de l'application, illustrant sa popularité et son efficacité dans la communauté de développement de logiciels.

💡Bootstrap

Bootstrap est un framework front-end gratuit et open-source pour le développement web. Il contient des modèles de conception basés sur HTML et CSS pour la typographie, les formulaires, les boutons, la navigation et d'autres composants d'interface, ainsi que des extensions JavaScript facultatives. Dans la vidéo, Bootstrap est utilisé pour accélérer le développement de l'interface utilisateur de l'application, en fournissant un ensemble cohérent et réactif de styles et de composants.

💡jQuery

jQuery est une bibliothèque JavaScript rapide, petite et riche en fonctionnalités. Elle simplifie des choses comme la manipulation de documents HTML, la gestion des événements, l'animation et Ajax avec une API facile à utiliser qui fonctionne sur une multitude de navigateurs. Dans le script, jQuery est utilisé pour ajouter des animations et faciliter la manipulation du DOM dans l'interface utilisateur de l'application.

💡JSON

JSON, qui signifie JavaScript Object Notation, est un format léger d'échange de données. Facile à lire et à écrire pour les humains, et facile à analyser et à générer pour les machines. Dans le contexte de la vidéo, JSON est utilisé pour stocker les données de l'application, comme la liste des tâches à faire, démontrant son utilité dans le stockage et l'échange de données structurées entre le frontend et le backend de l'application.

Highlights

Introduction to creating a modern GUI in Python using the 'eel' library.

Explanation of the 'eel' library and its similarity to Electron JS.

Demonstration of how 'eel' exposes Python functions to JavaScript and vice versa.

Starting the project by installing the 'eel' module using pip.

Creation of 'main.py' and the 'web' folder for HTML, CSS, and JS files.

Utilization of Bootstrap CSS and jQuery for attractive UI and animations.

Initialization of the eel's local web server with eel.init().

Launching the app window using eel.start().

Structure and setup of the 'index.html' file.

The necessity of including '/eel.js' in the HTML for eel's functionality.

Implementation of todo functionalities in 'main.py' using Python.

Usage of @eel.expose to allow JavaScript to call Python functions.

Adding dynamic functionality to the UI with 'script.js'.

Explanation of calling Python functions from JavaScript in 'script.js'.

Running the app to demonstrate the completed Todo application.

Conclusion and invitation for feedback.

Transcripts

play00:05

What’s up Pythoneers, this is Vishesh Dvivedi and welcome back to my channel All About Python.

play00:32

Today we are gonna talk about how you can create a modern looking graphical user interface

play00:37

in python using the ‘eel’ library.

play00:40

We are gonna talk about what eel is, how it works and how you can create your own desktop

play00:46

app with modern GUI in python.

play00:49

So without any further ado, let’s begin.

play00:53

When it comes to attractive graphical user interface, the first thing a software developer

play00:58

would think of is CSS.

play01:01

HTML along with CSS provides huge capabilities to designers to use their imaginations to

play01:07

create stunning UI.

play01:08

No other gui framework, technology or language can match HTML and CSS in its capabilities.

play01:16

So it’s fair to use HTML and css to create GUI in python.

play01:21

And that’s exactly what eel does.

play01:25

Eel is a simple library created to work similar to electron js.

play01:31

It runs a local web server whenever the python application is started, that exposes python

play01:37

functions to the javascript code and vice versa.

play01:40

A developer can easily create user interface in HTML and css, create core app functionalities

play01:47

in python and then use javascript on HTML side to call python functions or use python

play01:53

script to call javascript functions.

play01:55

Together, they can help a developer create great looking desktop apps, capable of performing

play02:01

amazing tasks.

play02:03

With the basics of eel clear, let’s create a sample todo desktop application in python

play02:09

to understand how it works.

play02:12

So as you can see I have my vscode editor opened here.

play02:17

Before we start, if you don’t have python and vscode setup in your system, i highly

play02:22

recommend watching this video where I have specified each and every step in downloading

play02:26

and installing python and setting up visual studio code with python.You can watch the

play02:31

video and then come back and continue with this one.

play02:35

So we will start by downloading and installing the eel module.

play02:39

Doing this in python is super easy, just open the terminal from vscode or your system and

play02:45

type

play02:46

```pip install eel```

play02:49

This command will download and install eel module within your system.

play02:53

Once the module is downloaded and installed, we are gonna start creating some files.

play03:00

First we will create a file named

play03:02

‘main.py’

play03:03

This file will contain all the python code we will use within our app.

play03:09

Next we will create a folder named

play03:12

‘web’

play03:13

This folder will contain al the HTML, CSS and JS files that we will use in our GUI.

play03:19

Within the web folder, we will create an

play03:22

‘index.html’

play03:23

File.

play03:24

This file will contain all of the HTML code that we will use.

play03:29

We will also create one

play03:32

‘script.js’

play03:33

File to store all of the javascript code that we will write.

play03:37

In order to create attractive UI easily, I a gonna use Bootstrap CSS here.

play03:43

To add bootstrap css, you can download the bootstrap files from its official site getbootstrap.com

play03:50

or you can get it from the repository link in the video’s description.

play03:54

I already have bootstrap files in another folder, so I am just gonna copy paste these

play03:59

files here.

play04:01

Similar to bootstrap, we are also gonna use jquery files to add a little animation to

play04:06

the UI.

play04:07

You can download jquery files from its site or from the repo.

play04:11

I will also copy the jquery folder here.

play04:14

With this, all of our required files are now created and we can start with the coding part

play04:20

of the project.

play04:21

We will start with the main.py file to first create a simple app window.

play04:28

First i will import the eel module by writing

play04:31

‘import eel’

play04:36

This line will simply import the eel module inside our python script.

play04:41

Next we will write

play04:46

eel.init(“web”)

play04:49

This line will start the eel’s local web server on the path specified inside the init

play04:55

function.

play04:56

Since we have stored all our files inside the ‘web’ folder, we will pass “web”

play05:01

as a string to the init function.

play05:04

Next we will write

play05:05

‘eel.start(“index.html”)’

play05:14

This line will start the chrome app and render the application window.

play05:19

You can specify the window size and some other parameters that you can view in the eel documentation

play05:25

(link in the description), but for now, we will go with the default window size and other

play05:30

settings.

play05:31

Note that we have passed “index.html” filename to the start function as this is

play05:36

the name of the file that we need to display when we start the app.

play05:40

We don’t need to specify the web folder here as eel will automatically look for this

play05:46

file inside the folder we have specified inside the init function..

play05:49

With just these three lines we should be able to see the app window when we run the app.

play05:56

In order to run it, we will open up a terminal window, either through vscode or through windows

play06:01

and type

play06:03

‘python main.py’

play06:06

and hit enter.

play06:08

As you can see, the app window has appeared on our screen.

play06:12

Right now it’s completely empty and also the window title is not right as we don’t

play06:18

have any code inside the index.html file.

play06:21

So now we will close the window and start working on the index.html file.

play06:27

Firstly, we will quickly write the necessary HTML tags like html, head, title, meta, body

play06:35

etc.

play06:36

Note that the text you write within the title tag will appear on the window title, so we

play06:42

will write Todo App here.

play06:44

This next step is very important to be performed for the eel module to work properly.

play06:50

Inside the body tag, we will add a script tag and within its src we will write

play06:57

‘/eel.js’

play06:59

Note that I haven’t created any eel.js file anywhere within the project, but this file

play07:04

will be created by the eel module.

play07:07

If this script is not imported within the html file, you’ll not be able to call javascript

play07:12

functions from python and vice versa, so make sure to add it.

play07:16

Now I will just fast forward a bit and quickly add the HTML code that I have previously written

play07:27

down.

play07:29

[FAST FORWARD]

play07:32

So i have added link to bootstrap css file here and have also given a grey background

play07:37

color to the body through the style tag here.

play07:40

If we scroll down, I have created a white div inside which are three main components:

play07:46

a welcome message, a div containing a label, input textbox (to enter todo name) and a button

play07:53

to add todo and finally a table to list all the todos.

play07:58

At the bottom of the file, I have imported three more js files, the jqyery file, the

play08:03

bootstrap file and the script js file that we had created.

play08:08

This is how our HTML file will look like right now.

play08:14

Now we will switch back to the main.py script to create some todo functionality.

play08:18

We will start creating functions between the eel.init and eel.start line.

play08:24

Now before we start typing, I just wanted to inform that this todo tool will store the

play08:29

todos data inside a json file kept inside the folder.

play08:34

Whenever we have to create, list or delete todos, we will read data from this file and

play08:39

write data onto this file.

play08:41

We dont need to create the JSON file ourselves as the script will do that for us.

play08:47

So first we will add the line

play08:49

‘Import json’

play08:51

To the top of the script to read and write onto json files.

play08:56

I will also add one more line before the import statement and after the init function call

play09:01

Todo_count = 0

play09:04

We will use this variable to keep track of the number of todos stored.

play09:11

Then we will create two functions read_data and write_data, so I will write

play09:16

‘def read_data(): With open(“data.json”, “r”) as file:

play09:19

Content = json.loads(file.read()) Return content

play09:20

def write_data(content): With open(“data.json”, “w”) as file:

play09:23

file.write(json.dumps(content)) Return content

play09:24

The read data function will read content from the json file and return it and the write

play09:31

data function will write data onto the json file.

play09:34

Next I will create four functions create_todo, list_todo and delete_todo.

play09:38

So i will write

play09:39

@eel.expose def create_todo(title):

play09:40

global todo_count new_todo = {

play09:41

“id”: todo_count + 1, “title”: title

play09:43

} content = read_data()

play09:44

content[‘todos’].append(new_todo) write_data(content)

play09:45

todo_count += 1 return new_todo

play09:46

Notice the eel.expose decorator.

play09:47

This decorator (as the name suggests) will expose this function to the GUI’s javascript

play09:51

file, which means that we can call this function from javascript, which we will in a few minutes.

play09:58

Within the create function, we first get the todo_count variable, then we create a new

play10:01

dictionary object new_todo representing the new todo.

play10:02

Each todo will have a id (which is the todo count + 1) and a title which will represent

play10:09

the user entered title which we receive from javascript.

play10:12

Then we will create the list_todo function

play10:14

@eel.expose def list_todo():

play10:15

Return read_data()

play10:16

As the name suggests, this function will list out all the todos that are stored within the

play10:23

json file.

play10:24

This function will also have eel.expose as this function will be called by the javascript

play10:30

code.

play10:31

Next we will create the delete_todo function

play10:34

@eel.expose def delete_todo(id):

play10:35

global todo_count

play10:36

content = read_data()

play10:37

for todo in content[‘todos’]: If todo[‘id’] == id:

play10:38

content[‘todos’].remove(todo)

play10:39

write_data(content) todo_count -= 1

play10:40

This function will be responsible to delete todos from the json file.

play10:45

This function will also be accessible by the javascript code.

play10:48

Within the function, we get the todo_count, iterate through the list of todos stored,

play10:57

find the todo to be delete by its id, remove the todo and then rewrite the file without

play11:05

the todo.

play11:06

Finally we wil write the last few lines of code we need for main.py file.

play11:12

We will write

play11:13

import os if not os.path.exists(“data.json”):

play11:15

file = open(“data.json”, “w”) file.write(json.dumps({“todos”: []}))

play11:16

file.close() else:

play11:17

content = read_data() todo_count = len(content[‘todos’])

play11:18

What this piece of code does is that it checks whether our json file is created or not.

play11:26

If its not created, then we create a blank one, else we just retrieve the number of todos

play11:33

already stored within the json file and save it in todo_count variable.

play11:40

With the python part done, let’s go switch to the script.js file to add some functionality

play11:45

and animation onto the html.

play11:49

I will not focus much on the explanation of the javascript functionalities not related

play11:53

to eel as they are out of scope, instead i will focus more on the eel related functionality.

play12:03

So first we will create three variables denoting three HTML elements: todo_title_input, todo_add_btn

play12:07

and, todo_table_body.

play12:08

The first one is the input textbox used to enter the new todo name, the second one is

play12:15

the button to add a new todo to the list and the third one is the tbody tag of the table

play12:24

which lists all the todos.

play12:25

Next we will create a function to display a todo on the HTML table.

play12:30

Since javascript function is a bit big, I will just quickly copy paste the code and

play12:35

explain it.

play12:36

eel.expose function displayTodo(todo)

play12:37

{ let tr = document.createElement("tr");

play12:38

let td1 = document.createElement("td"); td1.innerText = todo['title'];

play12:40

let td2 = document.createElement("td");

play12:41

let checkbox = document.createElement("input"); checkbox.setAttribute("data-id", todo['id']);

play12:43

checkbox.setAttribute("type", "checkbox"); checkbox.addEventListener("click", (event)

play12:44

=> {

play12:45

event.target.setAttribute("disabled", "true");

play12:46

let id = event.target.getAttribute("data-id"); eel.delete_todo(parseInt(id));

play12:47

// remove row from table and play animation let tr = event.target.parentElement.parentElement;

play12:51

$(tr).fadeTo("slow",0.001, function(){ $(this).remove();

play12:52

})

play12:53

});

play12:54

td2.appendChild(checkbox); tr.appendChild(td1);

play12:55

tr.appendChild(td2); todo_table_body.appendChild(tr);

play12:56

todo_title_input.value = ""; }

play12:57

This function looks a lot complicated that all the previous functions that we have written,

play12:58

but trust me what it does is really simple.

play12:59

This function takes a todo dictionary object as a parameter and creates row to be added

play13:03

onto the table with all the data of the todo.

play13:07

We have to note two things here.

play13:10

First eel.expose is written on top of the function, indicating that this function is

play13:16

exposed to the python code.

play13:18

I will explain in a bit why this is necessary.

play13:19

Also we can see that eel.delete_todo function is mentioned within this function.

play13:23

This shows how you can call a python function (exposed by eel) in javascript.

play13:28

The basic syntax is eel dot followed by the name of the python function.

play13:34

Next we will create a function to display all todos that will simply call the displayTodo

play13:43

function multiple times for each todo in a list.

play13:48

We will write

play13:49

eel.expose function displayAllTodos(todos){

play13:50

for (let todo of todos){ displayTodo(todo);

play13:54

} }

play13:55

We will use this function to load all the todos from the json file at the start of the

play14:12

app.

play14:13

Next we will create a javascript eventListener to be called everytime a user click on add

play14:22

todo button.

play14:23

We will write

play14:24

todo_add_btn.addEventListener("click", (event) => {

play14:26

let content = todo_title_input.value; if (content != "")

play14:30

{ eel.create_todo(content)(displayTodo)

play14:31

} })

play14:32

This event listener will get the todo name from the todo_title_input field and call the

play14:39

python script’s create_todo function to create a todo and store it in the json file.

play14:44

Notice the bracket after the create_todo(content) part with displayTodo inside it.

play14:50

Now here’s an important concept to understand.

play14:54

When we want to retrieve data from python using a javascript function, we need to pass

play14:59

a callback function from javascript side.

play15:02

In this case, the callback function is displayTodo.

play15:05

If we go back to create_todo function, we can see that the function returns the newly

play15:12

created todo in the form of dictionary.

play15:20

So what really happens is that javascript calls the create_todo function, python creates

play15:31

the new todo and adds it to the json file and then calls the function displayTodo (mentioned

play15:38

here) and passes the new_todo object as a parameter to the displayTodo function.

play15:46

That’s why the displayTodo function takes in todo as a parameter.

play15:53

Since python would call this function, we added eel.expose on top of it to provide python

play16:02

script access to the function.

play16:06

I hope I was able to explain the code functionality.

play16:10

In case if you didn’t understand you can try rewatching the video or ask your doubts

play16:18

in the comment section below.

play16:19

Finally we will add one more line of code at the end of the file

play16:25

eel.list_todo()(displayAllTodos)

play16:26

Just like i explained earlier, eel calls the list_todo function in python, which returns

play16:44

a list of all todos saved inside the json file.

play16:58

We also pass the displayAllTodos function to be called by the python script and

play17:20

the list of todos to be passed to

play17:42

this function.

play17:52

Then displayAllTodos would simply display all the todos on the UI.

play18:04

With this we finally complete the app.

play18:09

Now lets open a terminal and run python main.py to see how our app looks like

play18:16

As you can see we have our todo app here.

play18:19

We can enter the name of a new todo, for example ‘Creating video’, and click on add

play18:35

and our new todo will get added.

play18:39

We can enter more todos like ‘Play piano’ and add them to the list.

play18:49

We can click on any to-dos completed checkbox to mark it completed and remove it

play19:17

from the list.

play19:19

If we close the app and start it again, we can see that all the existing todos remain

play20:10

saved.

play20:12

With this, we end this tutorial on eel.

play20:37

I hope you liked the video, if you did don’t forget to like

play21:15

this video and subscribe to the channel.

play21:26

If you face any problems or issues, do mention them in

play21:38

the comments below and

play22:38

I will try my best to solve them.

play22:50

You can find all

play23:04

the resources used in the tutorial in the video’s description.

play23:21

With this, it’s time for me to go, this is Vishesh Dvivedi signing off.

Rate This

5.0 / 5 (0 votes)

Do you need a summary in English?