search
HomeBackend DevelopmentPython TutorialOne line of code converts a Python program into a graphical interface application

Project Gooey supports converting (almost) any Python 2 or 3 console program into a GUI application with one line of code.

One line of code converts a Python program into a graphical interface application

1. Quick start

Before you start, you must ensure that Python and pip have been successfully installed in On your computer, if not, you can visit this article: Super Detailed Python Installation Guide to install it.

If you use Python for data analysis, you can install Anaconda directly: Anaconda, a good helper for Python data analysis and mining, has built-in Python and pip.

In addition, it is recommended that you use VSCode Editor, it has many advantages: the best partner for Python programming—VSCode detailed guide.

Please choose any of the following methods to enter the command to install dependencies:

  1. Windows environment Open Cmd (Start-Run-CMD).
  2. MacOS environment Open Terminal (command space and enter Terminal).
  3. If you are using VSCode editor or Pycharm, you can directly use the Terminal at the bottom of the interface.

(Method 1) Install Gooey The simplest way is to install Gooey through PIP:

pipGooey

(Method 2). Alternatively, you can install Gooey

git clone https://github.com/chriskiehl/Gooey.git

by cloning the project to a local directory. After unzipping, enter the folder and run setup.py:

python setup.py install

2. How to use

Gooey By attaching a simple decorator to the main function, and then using GooeyParser you can The parameters that need to be used are visualized as text boxes, selection boxes or even file selection boxes.

For example, when downloading articles from scihub literature, we need to enter two parameters: 1. Keywords, 2. Number of downloaded articles, which can be changed using Gooey:

gooeyGooey, GooeyParser


 :
parser = GooeyParser(description=)
parser.add_argument(, help=, widget=)
parser.add_argument(, help=)
parser.add_argument(, help=)
args = parser.parse_args()
search(args.keywords, int(args.limit), args.path)

GooeyParser is the same as ArgumentParser. You can add input parameters using add_argument. The difference is that GooeyParser provides visual options:

parser.add_argument(, help=, widget=)

In this line of code, the widget parameter is provided to the args.path variable. A directory selector (widget="DirChooser") is provided. The help parameter is used to remind the user of the role of the selector. The effect is as follows:

One line of code converts a Python program into a graphical interface application

When you do not provide the widget parameter , the program uses the text input box by default.

parser.add_argument(, help=)
parser.add_argument(, help=)

One line of code converts a Python program into a graphical interface application

Gooey will automatically arrange your parameters, so you don't need to worry about the display of individual text boxes or selection boxes. in the code:

args = parser.parse_args()
search(args.keywords, int(args.limit), args.path)

args = parser.parse_args() can convert all the text input by the user into the variable value of the corresponding object, through args.var Extract the corresponding variable value directly.

The complete code and effect of this simple visualization program are as follows:

import asyncio
from scihub import SciHub
from gooey import Gooey, GooeyParser

 :
"""
搜索相关论文并下载

Args:
keywords (str): 关键词
limit (int): 篇数
path (str): 下载路径
"""
sh = SciHub()
result = sh.search(keywords, limit=limit)
print(result)

loop = asyncio.get_event_loop()
# 获取所有需要下载的scihub直链
tasks = [sh.async_get_direct_url(paper["url"]) for paper in result.get("papers", [])]
all_direct_urls = loop.run_until_complete(asyncio.gather(*tasks))
print(all_direct_urls)

# 下载所有论文
loop.run_until_complete(sh.async_download(loop, all_direct_urls, path=path))
loop.close()

@Gooey
 :
parser = GooeyParser(description="中文环境可用的scihub下载器 - @Python实用宝典")
parser.add_argument('path', help="下载路径", widget="DirChooser")
parser.add_argument('keywords', help="关键词")
parser.add_argument('limit', help="下载篇数")
args = parser.parse_args()
search(args.keywords, int(args.limit), args.path)

main()

If you want this code to run perfectly, please combine it with the scihub of the python super literature batch search and download tool that you have to know. py.

You can also use your own program for graphical interface, it doesn't matter.

The effect is as follows:

One line of code converts a Python program into a graphical interface application

##3. Supported widget components

All supported widget components are as follows:

1. Check box widget="CheckBox"

One line of code converts a Python program into a graphical interface application##2. Drop-down box

widget ="DropDown"

##3. Mutually exclusive selection boxOne line of code converts a Python program into a graphical interface application widget="RadioGroup"

4. Selection boxes for various target typesOne line of code converts a Python program into a graphical interface application

File selection box widget="FileChooser"

Directory selection box widget="DirChooser"

Multiple file selection Box widget="MultiFileChooser"

File saving directory widget="FileSaver"

One line of code converts a Python program into a graphical interface application

5.日期/时间选择器 widget="DateChooser/TimeChooser"

One line of code converts a Python program into a graphical interface application

6.密码输入框 wiget="PasswordField"

One line of code converts a Python program into a graphical interface application

7.多选列表框 widget="Listbox"

One line of code converts a Python program into a graphical interface application

8.颜色选择器 widget="ColourChooser"

One line of code converts a Python program into a graphical interface application

9.可过滤的下拉框 widget="FilterableDropdown"

One line of code converts a Python program into a graphical interface application

10.滑片 widget="Slider"

One line of code converts a Python program into a graphical interface application

四、打包

在一切都测试完毕后使用正常后,你可以通过 pyinstaller 将这个可视化程序打包成exe可执行文件。

1.编写 PyInstaller buildspec

PyInstaller使用 buildspec 来确定如何捆绑项目。你可以在Python实用宝典后台回复 buildspec下载 build.spec.txt.

下载后你只需要改两行代码:

One line of code converts a Python program into a graphical interface application

如下所示:

One line of code converts a Python program into a graphical interface application

在路径前面带r,可以不用输入两个斜杆 '' 哦。

2.执行打包命令

为了能够使用 PyInstaller, 我们需要使用pip安装这个模块:

pip install pyinstaller

然后进入 build.spec.text 所在文件夹,执行以下命令打包程序:

pyinstaller build.spec.txt

One line of code converts a Python program into a graphical interface application

打包完成后会在当前文件夹下生成一个dist文件夹,里面就包含了你打包生成的可执行文件,打包成功。


The above is the detailed content of One line of code converts a Python program into a graphical interface application. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor