How To Create Modern GUI In Python | Python Eel Tutorial
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
😀 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.
🚀 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.
📝 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.
🌐 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.
🎉 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
💡interface utilisateur graphique (GUI)
💡HTML
💡CSS
💡JavaScript
💡pip
💡Visual Studio Code (VSCode)
💡Bootstrap
💡jQuery
💡JSON
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
What’s up Pythoneers, this is Vishesh Dvivedi and welcome back to my channel All About Python.
Today we are gonna talk about how you can create a modern looking graphical user interface
in python using the ‘eel’ library.
We are gonna talk about what eel is, how it works and how you can create your own desktop
app with modern GUI in python.
So without any further ado, let’s begin.
When it comes to attractive graphical user interface, the first thing a software developer
would think of is CSS.
HTML along with CSS provides huge capabilities to designers to use their imaginations to
create stunning UI.
No other gui framework, technology or language can match HTML and CSS in its capabilities.
So it’s fair to use HTML and css to create GUI in python.
And that’s exactly what eel does.
Eel is a simple library created to work similar to electron js.
It runs a local web server whenever the python application is started, that exposes python
functions to the javascript code and vice versa.
A developer can easily create user interface in HTML and css, create core app functionalities
in python and then use javascript on HTML side to call python functions or use python
script to call javascript functions.
Together, they can help a developer create great looking desktop apps, capable of performing
amazing tasks.
With the basics of eel clear, let’s create a sample todo desktop application in python
to understand how it works.
So as you can see I have my vscode editor opened here.
Before we start, if you don’t have python and vscode setup in your system, i highly
recommend watching this video where I have specified each and every step in downloading
and installing python and setting up visual studio code with python.You can watch the
video and then come back and continue with this one.
So we will start by downloading and installing the eel module.
Doing this in python is super easy, just open the terminal from vscode or your system and
type
```pip install eel```
This command will download and install eel module within your system.
Once the module is downloaded and installed, we are gonna start creating some files.
First we will create a file named
‘main.py’
This file will contain all the python code we will use within our app.
Next we will create a folder named
‘web’
This folder will contain al the HTML, CSS and JS files that we will use in our GUI.
Within the web folder, we will create an
‘index.html’
File.
This file will contain all of the HTML code that we will use.
We will also create one
‘script.js’
File to store all of the javascript code that we will write.
In order to create attractive UI easily, I a gonna use Bootstrap CSS here.
To add bootstrap css, you can download the bootstrap files from its official site getbootstrap.com
or you can get it from the repository link in the video’s description.
I already have bootstrap files in another folder, so I am just gonna copy paste these
files here.
Similar to bootstrap, we are also gonna use jquery files to add a little animation to
the UI.
You can download jquery files from its site or from the repo.
I will also copy the jquery folder here.
With this, all of our required files are now created and we can start with the coding part
of the project.
We will start with the main.py file to first create a simple app window.
First i will import the eel module by writing
‘import eel’
This line will simply import the eel module inside our python script.
Next we will write
eel.init(“web”)
This line will start the eel’s local web server on the path specified inside the init
function.
Since we have stored all our files inside the ‘web’ folder, we will pass “web”
as a string to the init function.
Next we will write
‘eel.start(“index.html”)’
This line will start the chrome app and render the application window.
You can specify the window size and some other parameters that you can view in the eel documentation
(link in the description), but for now, we will go with the default window size and other
settings.
Note that we have passed “index.html” filename to the start function as this is
the name of the file that we need to display when we start the app.
We don’t need to specify the web folder here as eel will automatically look for this
file inside the folder we have specified inside the init function..
With just these three lines we should be able to see the app window when we run the app.
In order to run it, we will open up a terminal window, either through vscode or through windows
and type
‘python main.py’
and hit enter.
As you can see, the app window has appeared on our screen.
Right now it’s completely empty and also the window title is not right as we don’t
have any code inside the index.html file.
So now we will close the window and start working on the index.html file.
Firstly, we will quickly write the necessary HTML tags like html, head, title, meta, body
etc.
Note that the text you write within the title tag will appear on the window title, so we
will write Todo App here.
This next step is very important to be performed for the eel module to work properly.
Inside the body tag, we will add a script tag and within its src we will write
‘/eel.js’
Note that I haven’t created any eel.js file anywhere within the project, but this file
will be created by the eel module.
If this script is not imported within the html file, you’ll not be able to call javascript
functions from python and vice versa, so make sure to add it.
Now I will just fast forward a bit and quickly add the HTML code that I have previously written
down.
[FAST FORWARD]
So i have added link to bootstrap css file here and have also given a grey background
color to the body through the style tag here.
If we scroll down, I have created a white div inside which are three main components:
a welcome message, a div containing a label, input textbox (to enter todo name) and a button
to add todo and finally a table to list all the todos.
At the bottom of the file, I have imported three more js files, the jqyery file, the
bootstrap file and the script js file that we had created.
This is how our HTML file will look like right now.
Now we will switch back to the main.py script to create some todo functionality.
We will start creating functions between the eel.init and eel.start line.
Now before we start typing, I just wanted to inform that this todo tool will store the
todos data inside a json file kept inside the folder.
Whenever we have to create, list or delete todos, we will read data from this file and
write data onto this file.
We dont need to create the JSON file ourselves as the script will do that for us.
So first we will add the line
‘Import json’
To the top of the script to read and write onto json files.
I will also add one more line before the import statement and after the init function call
Todo_count = 0
We will use this variable to keep track of the number of todos stored.
Then we will create two functions read_data and write_data, so I will write
‘def read_data(): With open(“data.json”, “r”) as file:
Content = json.loads(file.read()) Return content
def write_data(content): With open(“data.json”, “w”) as file:
file.write(json.dumps(content)) Return content
The read data function will read content from the json file and return it and the write
data function will write data onto the json file.
Next I will create four functions create_todo, list_todo and delete_todo.
So i will write
@eel.expose def create_todo(title):
global todo_count new_todo = {
“id”: todo_count + 1, “title”: title
} content = read_data()
content[‘todos’].append(new_todo) write_data(content)
todo_count += 1 return new_todo
Notice the eel.expose decorator.
This decorator (as the name suggests) will expose this function to the GUI’s javascript
file, which means that we can call this function from javascript, which we will in a few minutes.
Within the create function, we first get the todo_count variable, then we create a new
dictionary object new_todo representing the new todo.
Each todo will have a id (which is the todo count + 1) and a title which will represent
the user entered title which we receive from javascript.
Then we will create the list_todo function
@eel.expose def list_todo():
Return read_data()
As the name suggests, this function will list out all the todos that are stored within the
json file.
This function will also have eel.expose as this function will be called by the javascript
code.
Next we will create the delete_todo function
@eel.expose def delete_todo(id):
global todo_count
content = read_data()
for todo in content[‘todos’]: If todo[‘id’] == id:
content[‘todos’].remove(todo)
write_data(content) todo_count -= 1
This function will be responsible to delete todos from the json file.
This function will also be accessible by the javascript code.
Within the function, we get the todo_count, iterate through the list of todos stored,
find the todo to be delete by its id, remove the todo and then rewrite the file without
the todo.
Finally we wil write the last few lines of code we need for main.py file.
We will write
import os if not os.path.exists(“data.json”):
file = open(“data.json”, “w”) file.write(json.dumps({“todos”: []}))
file.close() else:
content = read_data() todo_count = len(content[‘todos’])
What this piece of code does is that it checks whether our json file is created or not.
If its not created, then we create a blank one, else we just retrieve the number of todos
already stored within the json file and save it in todo_count variable.
With the python part done, let’s go switch to the script.js file to add some functionality
and animation onto the html.
I will not focus much on the explanation of the javascript functionalities not related
to eel as they are out of scope, instead i will focus more on the eel related functionality.
So first we will create three variables denoting three HTML elements: todo_title_input, todo_add_btn
and, todo_table_body.
The first one is the input textbox used to enter the new todo name, the second one is
the button to add a new todo to the list and the third one is the tbody tag of the table
which lists all the todos.
Next we will create a function to display a todo on the HTML table.
Since javascript function is a bit big, I will just quickly copy paste the code and
explain it.
eel.expose function displayTodo(todo)
{ let tr = document.createElement("tr");
let td1 = document.createElement("td"); td1.innerText = todo['title'];
let td2 = document.createElement("td");
let checkbox = document.createElement("input"); checkbox.setAttribute("data-id", todo['id']);
checkbox.setAttribute("type", "checkbox"); checkbox.addEventListener("click", (event)
=> {
event.target.setAttribute("disabled", "true");
let id = event.target.getAttribute("data-id"); eel.delete_todo(parseInt(id));
// remove row from table and play animation let tr = event.target.parentElement.parentElement;
$(tr).fadeTo("slow",0.001, function(){ $(this).remove();
})
});
td2.appendChild(checkbox); tr.appendChild(td1);
tr.appendChild(td2); todo_table_body.appendChild(tr);
todo_title_input.value = ""; }
This function looks a lot complicated that all the previous functions that we have written,
but trust me what it does is really simple.
This function takes a todo dictionary object as a parameter and creates row to be added
onto the table with all the data of the todo.
We have to note two things here.
First eel.expose is written on top of the function, indicating that this function is
exposed to the python code.
I will explain in a bit why this is necessary.
Also we can see that eel.delete_todo function is mentioned within this function.
This shows how you can call a python function (exposed by eel) in javascript.
The basic syntax is eel dot followed by the name of the python function.
Next we will create a function to display all todos that will simply call the displayTodo
function multiple times for each todo in a list.
We will write
eel.expose function displayAllTodos(todos){
for (let todo of todos){ displayTodo(todo);
} }
We will use this function to load all the todos from the json file at the start of the
app.
Next we will create a javascript eventListener to be called everytime a user click on add
todo button.
We will write
todo_add_btn.addEventListener("click", (event) => {
let content = todo_title_input.value; if (content != "")
{ eel.create_todo(content)(displayTodo)
} })
This event listener will get the todo name from the todo_title_input field and call the
python script’s create_todo function to create a todo and store it in the json file.
Notice the bracket after the create_todo(content) part with displayTodo inside it.
Now here’s an important concept to understand.
When we want to retrieve data from python using a javascript function, we need to pass
a callback function from javascript side.
In this case, the callback function is displayTodo.
If we go back to create_todo function, we can see that the function returns the newly
created todo in the form of dictionary.
So what really happens is that javascript calls the create_todo function, python creates
the new todo and adds it to the json file and then calls the function displayTodo (mentioned
here) and passes the new_todo object as a parameter to the displayTodo function.
That’s why the displayTodo function takes in todo as a parameter.
Since python would call this function, we added eel.expose on top of it to provide python
script access to the function.
I hope I was able to explain the code functionality.
In case if you didn’t understand you can try rewatching the video or ask your doubts
in the comment section below.
Finally we will add one more line of code at the end of the file
eel.list_todo()(displayAllTodos)
Just like i explained earlier, eel calls the list_todo function in python, which returns
a list of all todos saved inside the json file.
We also pass the displayAllTodos function to be called by the python script and
the list of todos to be passed to
this function.
Then displayAllTodos would simply display all the todos on the UI.
With this we finally complete the app.
Now lets open a terminal and run python main.py to see how our app looks like
As you can see we have our todo app here.
We can enter the name of a new todo, for example ‘Creating video’, and click on add
and our new todo will get added.
We can enter more todos like ‘Play piano’ and add them to the list.
We can click on any to-dos completed checkbox to mark it completed and remove it
from the list.
If we close the app and start it again, we can see that all the existing todos remain
saved.
With this, we end this tutorial on eel.
I hope you liked the video, if you did don’t forget to like
this video and subscribe to the channel.
If you face any problems or issues, do mention them in
the comments below and
I will try my best to solve them.
You can find all
the resources used in the tutorial in the video’s description.
With this, it’s time for me to go, this is Vishesh Dvivedi signing off.
浏览更多相关视频
Apprendre Photoshop en 5 MINUTES ! Tutoriel débutant
Peugeot 207 - Changement Disques + Plaquettes de frein avant
LE COURS : Notion de limite d'une fonction - Terminale
LE WEB - SNT Seconde
Comment vendre son ebook sur amazon et gagner de l'argent en ligne
Cette IA Crée une Application COMPLÈTE en 10 min ! IMPRESSIONNANT !
5.0 / 5 (0 votes)