gpt4 book ai didi

Electron 框架上的 Python

转载 作者:IT老高 更新时间:2023-10-28 20:56:55 32 4
gpt4 key购买 nike

我正在尝试使用 Web 技术(HTML5、CSS 和 JS)编写一个跨平台的桌面应用程序。我看了一些框架并决定使用 Electron 框架。

我已经用 Python 完成了应用程序,所以我想知道是否可以在 Electron 框架上使用 Python 编写跨平台桌面应用程序?

最佳答案

可以使用 Electron,但如果您正在寻找“网络” UI 功能,您可以查看 Flexx - 它允许您使用纯 Python 编写代码,但仍然使用 Web 开发工具的样式和 UI 灵 active 。

如果你坚持使用 Electron,你应该遵循这个 post 的想法。 .

首先确保你已经安装了所有东西:

pip install Flask
npm install electron-prebuilt -
npm install request-promise -g

现在创建您希望所有魔法发生的目录并包含以下文件

创建你的 hello.py:

from __future__ import print_function
import time
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World! This is powered by Python backend."

if __name__ == "__main__":
print('oh hello')
#time.sleep(5)
app.run(host='127.0.0.1', port=5000)

创建你的基本 package.json:

{
"name" : "your-app",
"version" : "0.1.0",
"main" : "main.js",
"dependencies": {
"request-promise": "*",
"electron-prebuilt": "*"
}
}

最后创建你的 main.js:

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
electron.crashReporter.start();

var mainWindow = null;

app.on('window-all-closed', function() {
//if (process.platform != 'darwin') {
app.quit();
//}
});

app.on('ready', function() {
// call python?
var subpy = require('child_process').spawn('python', ['./hello.py']);
//var subpy = require('child_process').spawn('./dist/hello.exe');
var rq = require('request-promise');
var mainAddr = 'http://localhost:5000';

var openWindow = function(){
mainWindow = new BrowserWindow({width: 800, height: 600});
// mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.loadURL('http://localhost:5000');
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function() {
mainWindow = null;
subpy.kill('SIGINT');
});
};

var startUp = function(){
rq(mainAddr)
.then(function(htmlString){
console.log('server started!');
openWindow();
})
.catch(function(err){
//console.log('waiting for the server start...');
startUp();
});
};

// fire!
startUp();
});

取自帖子本身 - 是以下注释

Notice that in main.js, we spawn a child process for a Python application. Then we check whether the server has been up or not using unlimited loop (well, bad practice! we should actually check the time required and break the loop after some seconds). After the server has been up, we build an actual electron window pointing to the new local website index page.

关于 Electron 框架上的 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32158738/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com