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)

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

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.

See all articles