أحمد
رئيسية كتب بودكاست تعلم شهادات تطبيقات بحث

تنبيه

الرجاء تحديد نص من المقال أولاً.

محتوى محمي

لتحميل هذا المقال، يرجى تفعيل جرس الإشعارات أو اختيار طريقة اشتراك أخرى.

Ahmed Bouchefra

الرئيسية
Ahmed Bouchefra

أحمد بوشفرة

Software Engineer & Tech Author

ابدأ هنا
ابدأ هنا
المكتبة
المكتبة
أكاديمية بايثون
أكاديمية بايثون
تطبيق اختبارات البرمجة
تطبيق اختبارات البرمجة
دورات يوديمي
دورات يوديمي
المسارات
المسارات
الملخصات
الملخصات
الأدوات
الأدوات
اشترك
اشترك
كتب فريق 10xdevblog
كتب فريق 10xdevblog
الكاتب: أحمد بوشفرة

Using Python with Electron Tutorial

اضغط على زر PDF لتحميل المقال كملف للقراءة لاحقاً

ملاحظة: هذا المقال بقلم أحمد بوشفرة. الآراء الواردة تعبر عن الكاتب.

أحمد بوشفرة: مبرمج ومؤلف تقني، أساعد المطورين على بناء تطبيقات ويب حديثة وسريعة.

يمكنك التواصل مع الكاتب لطلب خدمات برمجية عبر:

يمكنك أيضاً نشر مقالك هنا والترويج لخدماتك أمام جمهور من المبرمجين. تواصل معنا

لخص هذا المقال باستخدام ChatGPT

انسخ الأمر أدناه والصقه في ChatGPT للحصول على ملخص سريع للمقال:

لخص لي هذا المقال في نقاط رئيسية: https://www.ahmedbouchefra.com/using-python-with-electron-tutorial/ تم النسخ!
فتح ChatGPT

In this tutorial, you’ll learn to build GUIs for your Python applications using Electron and web technologies i.e HTML, CSS and JavaScript-this means taking advantage of the latest advancements in front-end web development to build desktop applications but also taking advantages of Python and the powerful libraries it has to easily implement advanced requirements.

You can find the code in this GitHub repository.

Creating your First Electron Application

Let’s now see how to create our first Electron application. You can develop Electron apps just like you would normally develop Node.js apps.

You first need to start with creating or generating a package.json file inside your project’s folder using the following command:

npm init -y

This will create a basic package.json file with default values:

{
  "name": "electronjs-python",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Next, create the two index.html and main.js files inside the project’s folder.

touch main.js index.html

The main.js file is the main script so we need to change the main property of our package.json file to main.js instead of the default index.js file (It’s only a preference not required):

"main": "main.js",

Next, you need to install electron from npm:

npm install --save-dev electron

This will install electron locally; you can also follow the official guide for more available options for installing electron.

Next, add the start script to run the main.js file. Open the package.json file and add:

  "scripts": {
    "start": "electron .",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Now, let’s add the code which runs a GUI window in the main process. Open the main.js file and add, the first line to import the electron module:

const {app, BrowserWindow} = require('electron')

Next, add the following function which makes an instance of BrowserWindow and load the index.html file:

  function createWindow () {
    window = new BrowserWindow({width: 800, height: 600})
    window.loadFile('index.html')
  }

When the application is ready, run the createWindow() method:

  app.on('ready', createWindow)

We can also handle different events such as when closing all Windows using:

  app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

Finally, let’s add the following content to the index.html file:

<!DOCTYPE html>
  <html>
    <head>
      <meta charset="UTF-8">
      <title>Hello Python from Electron!</title>
    </head>
    <body>
      <h1>Hello Python!</h1>
    </body>
  </html>

Now, you can run the application using:

npm start

This is a screenshot of the application running:

Electron Python

Running a Python Script from Electron

Since we want to develop our application using Python and use Electron to build the GUI frontend with the web; we need to be able to communicate between Python and Electron.

Let’s see how to run a basic Python script from Electron. First create a hello.py file and add the following Python code which prints Hello from Python! to the standard output:

import sys
print('Hello from Python!')
sys.stdout.flush()

In your main.js file, run the following code to spawn a Python process and execute the hello.py script:

function createWindow () {
    /*...*/
    var python = require('child_process').spawn('python', ['./hello.py']);
    python.stdout.on('data',function(data){
	    console.log("data: ",data.toString('utf8'));
    });
 }

Electron Python

Using python-shell to Communicate between Python and Node.js/Electron

A better way to communicate with Node.js/Electron and Python is through using the python-shell package.

python-shell provides an easy way to run Python scripts from Node.js with basic and efficient inter-process communication and better error handling.

Using python-shell, you can:

  • spawn Python scripts in a child process;
  • switch between text, JSON and binary modes;
  • use custom parsers and formatters;
  • perform data transfers through stdin and stdout streams;
  • get stack traces when an error is thrown.

Head back to your terminal, make sure you are inside the root folder of your project and run the following command to install python-shell from npm:

npm install --save python-shell 

You can then simply run a Python shell using:

var pyshell =  require('python-shell');

pyshell.run('hello.py',  function  (err, results)  {
 if  (err)  throw err;
 console.log('hello.py finished.');
 console.log('results', results);
});

Electron python-shell

Conlusion

In this tutorial, we’ve seen how to use Electron and Python to build a simple desktop application.

We’ve also seen how to use the python-shell module to run a Python shell from a Node.js/Electron application and communicate between Electron and Python.

هل لديك سؤال أو استفسار؟ اترك تعليقاً بالأسفل:

احصل على المحتوى الجديد فور نشره ⚡

اختر الطريقة الأنسب لك لمتابعتنا والحصول على التحديثات مجاناً.
(اضغط على رابط التفعيل الذي سيصلك لفتح المحتوى)

عرض كل بدائل الاشتراك

احصل على موارد مجانية! 📚

اشترك في القائمة البريدية واحصل على كتب ومصادر تعليمية مجانية

تنبيه هام:

للاشتراك بنجاح، يرجى فتح الصفحة في متصفح خارجي (مثل Chrome أو Safari) وليس متصفح التطبيق المدمج.

📚 المكتبة المجانية

حمّل كتب وأدلة PDF مجانية في البرمجة وتطوير الويب

تصفح المكتبة

شارك المقال

Using Python with Electron Tutorial
0:00 / 0:00