Table of Contents
Conception
The artifact appears
Connecting with Flask
Directory problem
完美呈现
注意:
总结
参考代码
Home Backend Development Python Tutorial Python tips can still implement graphical interface without using Gui

Python tips can still implement graphical interface without using Gui

Apr 12, 2023 pm 04:43 PM
python interface gui

If 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
Copy after login

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()
Copy after login
  • 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:

Python tips can still implement graphical interface without using Gui

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__) # 创建一个应用

@app.route('/') 
def index():# 定义根目录处理器
return render_template('index.html')

@app.route('/detail')
def detail():
return render_template('detail.html') 

if __name__ == '__main__':
app.run() # 启动服务
Copy after login

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()
Copy after login
  • 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:

Python tips can still implement graphical interface without using Gui

Connecting to Flask

Directory problem

Now you can package this project into an exe.

First you need to install pyinstaller[4]

pip install pyinstaller
Copy after login

Then enter the program directory to execute:

pyinstall -F -w main.py
Copy after login
  • 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!

Python tips can still implement graphical interface without using Gui

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.

完美呈现

如何解决这个问题呢?

作为不使用外部数据或文件的程序,只需要将程序本身打包就可以了,但大部分程序都需要外部数据,比如我们的 Flask 应用,就需要用到静态文件等。

那么如何将它们打包进可执行文件呢?

只需要在打包时多加一个参数就可以了:

pyinstaller main.py -F -w --add-data "./templates/*;templates"
Copy after login

-- add-data 参数表示添加额外的数据 -- ./templates/* 表示需要添加当前目录的 templates 目录中的所有文件 -- ;为分隔符,其后的 templates 表示解压是这些数据所在的目录,这个目录名必须和 创建 app 时 template_folder 参数一致 -- 如果需要用到静态文件,需要额外添加,比如 --add-data "./static/*;static"

这样就能将外部数据一起打包进来了。

打包好后,双击执行,就会发现网页得以完美呈现了。

注意:

如果使用了虚拟环境,必须在虚拟环境中单独安装 pyinstaller,而不能用其他环境中已经安装好的,这是为了包装打包是可以链接所以程序引用的模块

因为 pyinstaller 打包时,找不到被引用的模块时并不报错,而打包好的程序可能会无法执行。

总结

经过一番折腾,终于在客户要求的时间之前将工作完成了,特别高兴。

回头一想,多亏用了 Python 作为主要的开发语言,因为 Python 强悍的社区支持没有找不到的解决方法。

这次经历的另一个启示就是,遇到问题,不要着急就做,可以先想一想,是否有更好的方法,特别在使用 Python 的时候。

比心!

参考代码

​https://www.php.cn/link/0c52d419a421fb13bb58357e67b7fb4b​

[1]Electron: https://www.electronjs.org/

[2]Pywebview: https://pywebview.flowrl.com/

[3]虚拟环境: 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles