Electron as GUI of Python

无人久伴 提交于 2020-08-07 18:56:32

最近准备做一个离线升级工具,想起前几天刚接触的Electron 决定用它与python相结合来完成

开始准备环境搭建

几经折腾各种zerorpc,zerormq各种报错

历经一天多的网上折腾终于找到一篇实践成功

先看整个流程搭建:

start
 |
 V
+------------+
|            | start
|            +-------------> +-------------------+
|  electron  | sub process   |                   |
|            |               | python web server |
| (basically |     http      |                   |
|  browser)  | <-----------> | (business logic)  |
|            | communication |                   |
|            |               | (all html/css/js) |
|            |               |                   |
+------------+               +-------------------+

 

start
 |
 V
+--------------------+
|                    | start
|  electron          +-------------> +------------------+
|                    | sub process   |                  |
| (browser)          |               | python server    |
|                    |               |                  |
| (all html/css/js)  |               | (business logic) |
|                    |   zerorpc     |                  |
| (node.js runtime,  | <-----------> | (zeromq server)  |
|  zeromq client)    | communication |                  |
|                    |               |                  |
+--------------------+               +------------------+

 

下来安装步骤(windows):

Remove-Item "$($env:USERPROFILE)\.node-gyp" -Force -Recurse -ErrorAction Ignore Remove-Item "$($env:USERPROFILE)\.electron-gyp" -Force -Recurse -ErrorAction Ignore Remove-Item .\node_modules -Force -Recurse -ErrorAction Ignore


npm install --runtime=electron --target=1.7.6(版本很重要)

这里我直接远程连接的同事的python环境,修改下面文件:

//main.js
let mainWindow = null

const createWindow = () => {
  mainWindow = new BrowserWindow({width: 800, height: 600})
  mainWindow.loadURL(require('url').format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
  mainWindow.webContents.openDevTools()

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

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

  

const zerorpc = require("zerorpc")
let client = new zerorpc.Client()

client.connect("tcp://192.168.200.51:4242")

client.invoke("echo", "server ready", (error, res) => {
  if(error || res !== 'server ready') {
    console.error(error)
  } else {
    console.log(res)
  }
})

let formula = document.querySelector('#formula')
let result = document.querySelector('#result')

formula.addEventListener('input', () => {
  client.invoke("calc", formula.value, (error, res) => {
    if(error) {
      console.error(error)
    } else {
		
      result.textContent = res
    }
  })
})

formula.dispatchEvent(new Event('input'))

 

下来就可以启动:
npm run start


参考地址(相当不错):https://github.com/fyears/electron-python-example



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!