


Python tips can still implement graphical interface without using Gui
Apr 12, 2023 pm 04:43 PMIf there is something that programmers are afraid of, then I think it may be - the needs have changed again!
No, the customer said after the author developed a browser-based Web application: Program It needs to be run in an internal (no) internal (network) environment...
This means that the Python environment cannot be installed!
Who calls us programmers? Why not develop a GUI version? No, it’s not a problem for me...
But after hearing the time given, I couldn’t calm down anymore...
In order not to affect the customer’s evaluation, we can only give one week!
Conception
Although it is not difficult to create a GUI, it does require sorting out the services and the interactive interfaces with users. If not, you will have to write a separate interface for the GUI, which is obviously not enough time.
No, just think of another way...
Otherwise, just package the web application into an executable program and copy it to the machine to run. There are many similar frameworks, such as Nodejs. Electron[1], Pywebview[2] in Python.
Just wrap the original Web program, then just do it!
The artifact appears
The Web program is developed with Flask, so Python needs to be installed Pywebview as packaging tool.
Create a virtual environment [3] or in the original Web project environment, execute:
pip install pywebview
In Windows system, .Net 4.0 or above is required
Try it out:
import webview window = webview.create_window('Hello!', 'http://http://www.justdopython.com') webview.start()
- Reference the webview library
- Start a window, set the title to Hello!, and specify the page address
- Start webview
You can see the following effect:
Try it first
It’s amazing!
Pywebview supports three modes, simple mode and server mode and thread mode.
Simple mode is equivalent to a customized streaming browser. You can browse by specifying an address, as in the example above.
Server mode is equivalent to packaging a Web application, which means it will start a local server and browse in a customized browser.
Thread mode is more advanced, which means you need to manually maintain the thread status to achieve more advanced gameplay.
For the current needs, we choose the server mode, which is to package a local Web application.
Connecting with Flask
The server mode will provide us with an HTTP Server, as long as the web application is deployed on it.
Because it just shows the code of the actual project, here is a simple Flask application:
Regarding Flask Web application development, you can refer to the Flask article written by the author before
Create one app.py file:
from flask import Flask, render_template, jsonify, request app = Flask(__name__) # 創(chuàng)建一個(gè)應(yīng)用 @app.route('/') def index():# 定義根目錄處理器 return render_template('index.html') @app.route('/detail') def detail(): return render_template('detail.html') if __name__ == '__main__': app.run() # 啟動(dòng)服務(wù)
This application is very simple, with only two pages, accessed through / and /detail.
If you run this code, a Flask application will be started and accessed through http://120.0.0.1:5000.
How to install it in Pywebview?
It’s very simple:
import webview from app import app if __name__ == '__main__': window = webview.create_window('Pywebview', app, height=600, width=1000) webview.start()
- Introduce webview
- Introduce the app you just created
- Create a webview window and pass app as the url parameter
- Then start the webview
The key here is to use the Flask application as the url parameter. Webview finds that the passed If the parameter entered is the flask application, the service mode will be started.
After running the program, you can see the same effect as in the browser:
Connecting to Flask
Directory problem
Now you can package this project into an exe.
First you need to install pyinstaller[4]
pip install pyinstaller
Then enter the program directory to execute:
pyinstall -F -w main.py
- The F parameter means packaging the program into an executable file, without adding This parameter will be packaged into a folder
- The w parameter indicates that the command line window will not be displayed when executing the packaged executable program. This feature is only available in Windows systems
Soon, a dist folder will be generated in the program directory, and there will be a main.exe executable file in it. This is the packaged result.
Double-click to run and you can see the effect...
Wait, it doesn’t seem to be what you imagined!
Connect to Flask
What is going on?
According to the prompt, it is because the template file of the page cannot be found.
When we created the Flask app earlier, we used the default template path, which is the templates directory of the directory where the app.py file is located. Why can’t it be found after packaging?
This This is because in Windows, when the executable file is run, it will be decompressed to a specific directory, and our template file is not packaged into the exe file, so the template file cannot be found during runtime.
完美呈現(xiàn)
如何解決這個(gè)問(wèn)題呢?
作為不使用外部數(shù)據(jù)或文件的程序,只需要將程序本身打包就可以了,但大部分程序都需要外部數(shù)據(jù),比如我們的 Flask 應(yīng)用,就需要用到靜態(tài)文件等。
那么如何將它們打包進(jìn)可執(zhí)行文件呢?
只需要在打包時(shí)多加一個(gè)參數(shù)就可以了:
pyinstaller main.py -F -w --add-data "./templates/*;templates"
-- add-data 參數(shù)表示添加額外的數(shù)據(jù) -- ./templates/* 表示需要添加當(dāng)前目錄的 templates 目錄中的所有文件 -- ;為分隔符,其后的 templates 表示解壓是這些數(shù)據(jù)所在的目錄,這個(gè)目錄名必須和 創(chuàng)建 app 時(shí) template_folder 參數(shù)一致 -- 如果需要用到靜態(tài)文件,需要額外添加,比如 --add-data "./static/*;static"
這樣就能將外部數(shù)據(jù)一起打包進(jìn)來(lái)了。
打包好后,雙擊執(zhí)行,就會(huì)發(fā)現(xiàn)網(wǎng)頁(yè)得以完美呈現(xiàn)了。
注意:
如果使用了虛擬環(huán)境,必須在虛擬環(huán)境中單獨(dú)安裝 pyinstaller,而不能用其他環(huán)境中已經(jīng)安裝好的,這是為了包裝打包是可以鏈接所以程序引用的模塊
因?yàn)?pyinstaller 打包時(shí),找不到被引用的模塊時(shí)并不報(bào)錯(cuò),而打包好的程序可能會(huì)無(wú)法執(zhí)行。
總結(jié)
經(jīng)過(guò)一番折騰,終于在客戶要求的時(shí)間之前將工作完成了,特別高興。
回頭一想,多虧用了 Python 作為主要的開發(fā)語(yǔ)言,因?yàn)?Python 強(qiáng)悍的社區(qū)支持沒(méi)有找不到的解決方法。
這次經(jīng)歷的另一個(gè)啟示就是,遇到問(wèn)題,不要著急就做,可以先想一想,是否有更好的方法,特別在使用 Python 的時(shí)候。
比心!
參考代碼
??http://ipnx.cn/link/0c52d419a421fb13bb58357e67b7fb4b??
[1]Electron: https://www.electronjs.org/
[2]Pywebview: https://pywebview.flowrl.com/
[3]虛擬環(huán)境: https://mp.weixin.qq.com/s/WflK5pOKhvPg8zrf_W5mfw
[4]pyinstaller: https://pyinstaller.readthedocs.io/en/stable/
The above is the detailed content of Python tips can still implement graphical interface without using Gui. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

When choosing a suitable PHP framework, you need to consider comprehensively according to project needs: Laravel is suitable for rapid development and provides EloquentORM and Blade template engines, which are convenient for database operation and dynamic form rendering; Symfony is more flexible and suitable for complex systems; CodeIgniter is lightweight and suitable for simple applications with high performance requirements. 2. To ensure the accuracy of AI models, we need to start with high-quality data training, reasonable selection of evaluation indicators (such as accuracy, recall, F1 value), regular performance evaluation and model tuning, and ensure code quality through unit testing and integration testing, while continuously monitoring the input data to prevent data drift. 3. Many measures are required to protect user privacy: encrypt and store sensitive data (such as AES

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

The core idea of PHP combining AI for video content analysis is to let PHP serve as the backend "glue", first upload video to cloud storage, and then call AI services (such as Google CloudVideoAI, etc.) for asynchronous analysis; 2. PHP parses the JSON results, extract people, objects, scenes, voice and other information to generate intelligent tags and store them in the database; 3. The advantage is to use PHP's mature web ecosystem to quickly integrate AI capabilities, which is suitable for projects with existing PHP systems to efficiently implement; 4. Common challenges include large file processing (directly transmitted to cloud storage with pre-signed URLs), asynchronous tasks (introducing message queues), cost control (on-demand analysis, budget monitoring) and result optimization (label standardization); 5. Smart tags significantly improve visual

To integrate AI sentiment computing technology into PHP applications, the core is to use cloud services AIAPI (such as Google, AWS, and Azure) for sentiment analysis, send text through HTTP requests and parse returned JSON results, and store emotional data into the database, thereby realizing automated processing and data insights of user feedback. The specific steps include: 1. Select a suitable AI sentiment analysis API, considering accuracy, cost, language support and integration complexity; 2. Use Guzzle or curl to send requests, store sentiment scores, labels, and intensity information; 3. Build a visual dashboard to support priority sorting, trend analysis, product iteration direction and user segmentation; 4. Respond to technical challenges, such as API call restrictions and numbers

The core of PHP's development of AI text summary is to call external AI service APIs (such as OpenAI, HuggingFace) as a coordinator to realize text preprocessing, API requests, response analysis and result display; 2. The limitation is that the computing performance is weak and the AI ecosystem is weak. The response strategy is to leverage APIs, service decoupling and asynchronous processing; 3. Model selection needs to weigh summary quality, cost, delay, concurrency, data privacy, and abstract models such as GPT or BART/T5 are recommended; 4. Performance optimization includes cache, asynchronous queues, batch processing and nearby area selection. Error processing needs to cover current limit retry, network timeout, key security, input verification and logging to ensure the stable and efficient operation of the system.

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[
