Hi ππ
In this tutorial, we will learn how to create a modern user interface using HTML, CSS, and JS in Python. We will start by creating a basic HTML structure, then we will add CSS to style the elements, and finally, we will add JS to add interactivity.
In this tutorial, I will use a module called eel
Eel is a little Python library for making simple Electron-like offline HTML/JS GUI apps, with full access to Python capabilities and libraries.
Install eel
pip install eel
Step 1
Create HTML, CSS, JS files and save them into folder named web
Step 2
Create main.py
file
import eel eel.init('web') eel.start('index.html')
result
Change Height and width of eel window
import eel eel.init('web') eel.start('index.html', size = (800, 500))
Step 3
Add some CSS style and div
CSS File:
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap'); body { margin: 0; padding: 0; font-family: 'Poppins', sans-serif; } .text { font-weight: bold; margin: 100px auto; width: 80%; background-color: beige; text-align: center; padding: 20px; font-size: 22px; }
HTML File:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="text"> Hello, World </div> </body> </html>
result
Add javascript and get returned value from python function
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="text"> Hello, World </div> <script src="/eel.js"></script> <script src="main.js"></script> </body> </html>
In addition to the files in the frontend folder, a Javascript library will be served at /eel.js. You should include this in any pages
main.py
import eel eel.init('web') @eel.expose def hello(): return 'Hello World From Pyhton' eel.start('index.html', size = (800, 500))
main.js
let text = document.querySelector('.text'); async function get_value_from_python () { let msg = await eel.hello()(); text.textContent = msg } get_value_from_python()
result
Send data from Javascript to Python
main.js
eel.expose(js_random); function js_random() { return Math.random(); }
main.py
import eel eel.init('web') def print_num(n): print('Got this from Javascript:', n) # Call Javascript function, and pass explicit callback function eel.js_random()(print_num) eel.start('index.html', size = (800, 500))
learn more: https://github.com/python-eel/Eel
Now we're done π€
Don't forget to like and follow π
Support me on PayPal π€
https://www.paypal.com/paypalme/amr396
Top comments (0)