Electron as GUI of Python


最近准備做一個離線升級工具,想起前幾天剛接觸的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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM