Python_Gooey和pyinstaller打造易用的工具

Python沟通

 Python 搭建 GUI 界面时,首选Gooey ,然后 PyQt5 和 Tkinter, 
 Pyinstaller
  : --paths 后接第三方模块的路径,多个路径直接用逗号分隔(英文逗号)
   -F 后接源文件路径
   使用-F,只生成一个大的可执行文件
   --clean 表示清理打包完成后的临时文件(可选,但建议写上)
   打包多个.py文件

    打包的py文件(并记录好文件路径),以及第三方库的路径
    
    我的源文件路径 D:\《Numpy数据处理详解》电子书\打包\pyinstaller学习.py
    
    我的用到的第三方库  C:\Users\huawei\AppData\Roaming\Python\Python39\site-packages\pandas,xlwings
     
    pyinstaller -F pyinstaller学习.py --paths C:\Users\huawei\AppData\Roaming\Python\Python39\site-packages\pandas,xlwings --clean

安装

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple Gooey
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jieba

需求示例

功能:输入:文件地址,输出:显示词频最高的十个词语
       输入是GUI的形式
	      地址框,执行框
原理: 打包第三方库		

代码示例

#!/usr/bin/python3
# -*- coding: utf-8 -*- 

import jieba
from gooey import Gooey, GooeyParser
import argparse

def get_file_words(input_file):
    words =[]
    with open(input_file,mode="r",encoding="utf8") as fw:
        lines = fw.readlines()
        for line in lines:
            line = line.replace("\r","").replace("\r","").strip().replace(' ','')
            cut_word_list = jieba.cut(line,cut_all=False) 
            stopwords=[':','“','!','”',' ',',','、']
            for sig_word in cut_word_list:
                if sig_word not in stopwords:
                    words.append(sig_word)
    return words

def get_freq(words):
    # 统计每一个汉字的出现次数,使用字典的形式进行统计
    result = {}
    for word in words:
        res = result.get(word, 0)
        if res == 0:
            result[word] = 1
        else:
            result[word] = result[word] + 1

    result = sorted(result.items(),  key=lambda kv:(kv[1], kv[0]), reverse=True)
    return result
  
def regular_main():
    parser =  argparse.ArgumentParser(description="My Cool !")
    parser.add_argument('--filename', help="name of the file to process", default=r'D:\annotation\info.txt') 
    args = parser.parse_args() 
    exp_file_nm = args.filename
    exp_word = get_file_words(exp_file_nm)
    exp_freq = get_freq(exp_word)
    print(exp_freq[:5])

### 
@Gooey(program_name="stat tools", encoding='utf-8',)
def main():
    parser =  GooeyParser(description="My Cool !")
    parser.add_argument('filename',
                        metavar='Input file',
                        help='The file for which you want to static freq',
                        widget='FileChooser')
    args = parser.parse_args() 
    exp_file_nm = str(args.filename)
    exp_word = get_file_words(exp_file_nm)
    exp_freq = get_freq(exp_word)
    print(exp_freq[:5]) 

if __name__ == '__main__':  
    #regular_main()
    main()

打包可执行程序

 Gooey 通过将一个简单的装饰器附加到主函数上,
 然后使用GooeyParser可将你所有需要用到的参数可视化为文本框、选择框甚至是文件选择框
  --表示可选参数。不加--就是必选
  Gooey 是一个 Python GUI 程序开发框架,基于 wxPython GUI 库
 widget="DirChooser"
 widget='FileChooser'
 
 一个py放一个@Gooey
 @Gooey(program_name="工具", encoding='utf-8', program_description="")
 dump_build_config=True
  dump_build_config	Boolean	将设置以 JSON 格式保存在硬盘中以供编辑/重用。
  target 执行命令的程序
  
 ,Gooey打包exe方法跟普通打包方式不一样,需要使用pyinstaller build.spec 
   find = partial(re.search, string=text.strip().decode("gbk")) 
   #decode默认参数self.encoding 改为gbk打包即可显示中文
  
import gooey
gooey_root = os.path.dirname(gooey.__file__)
gooey_languages = Tree(os.path.join(gooey_root, 'languages'), prefix = 'gooey/languages')
#gooey_images = Tree(os.path.join(gooey_root, 'images'), prefix = 'gooey/images')

a = Analysis(['my_justTest.py'],
             pathex=['C:\my\Python38\python.exe'],
             hiddenimports=[],
             hookspath=None,
             runtime_hooks=None,
             )
pyz = PYZ(a.pure)

options = [('u', None, 'OPTION')]

exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          options,
          gooey_languages, # Add them in to collected files
          name='CHANGE_ME_myjustTest',
          debug=False,
          strip=None,
          upx=True,
          console=False,
       )      		  

CLI-命令行界面

  argparse  

进度条

 tqdm   

GUI工具库

 MFC(Microsoft Foundation Classes,微软基础类库)--MFC界面库,C/C++混合-事件驱动架构--构建于Windows API 之上
 跨平台的GUI工具库,较为有名的当属 GTK+、Qt 和 wxWidgets 
 GTK  GTK+(GIMP Toolkit)是一套源码以LGPL许可协议分发、跨平台的图形工具包--GIMP Toolkit(GTK+  C的开源GUI库
     Qt 采用的信号与槽机制
     wx 采用的是事件驱动型的编程机制 C++的wxWidget库 
 OpenGL  是用于渲染 2D、3D 矢量图形的跨语言、跨平台的应用程序编程接口

JAVA的GUI框架----AWT , SWT, Swing

Python GUI工具库

 Tkinter   :是python最简单的图形化模块,总共只有14种组建
  PyQt     :是python最复杂也是使用最广泛的图形化
   wxPython :是python当中居中的一个图形化,学习结构很清晰
  PyGtk   :在三大平台(windwos/Linux/Mac)上运行底层的Gtk+库
   Pywin    :是python windows 下的模块,摄像头控制(opencv),常用于外挂制作  
  Kivy 则适合做3D程序
  Gooey 是一个 Python GUI 程序开发框架,基于 wxPython GUI 库

图像

  开源视觉库,从二维(2D)逐步发展到三维(3D)并已经日益成熟。
 OpenCV版本为4.1.2+,Open3D版本为0.8
    Open3D: A Modern Library for 3D Data Processing	
   PIL(Python Image Library), Pillow 
   Scikit-image  
   Matplotlib	 Seaborn Plotly 

Web 框架

 Java中 spring  spring-boot
  Python	:
    Streamlit:Data Professor 的 《Build 12 Data Science Apps with Python and Streamlit - Full Course》 
    Flask和Django框架的数据应用,前端工具(比如HTML和CSS以及JavaScript)是一种必须的知识
Shiny 是一个为 R 模型提供 Web 交互界面的应用框架,非常容易编写应用,不要求有 Web 开发技能	

wxWidget

 实现窗口,面板 事件
    wxFrame  wxPanel wxPaintEvent
    wxWidgets窗口程序需要四个必须的部分:
     1、添加一个继承wxApp的应用程序类。
     2、添加一个继承wxFrame的框架类。
     3、重载wxApp::OnInit()成员函数,并在其中创建框架类的对象。
     4、在调用宏定义IMPLEMENT_APP()实例化应用程序。
	wxPaintEvent是绘制事件类

wxPython

 pip install -U wxPython
 
 概念:
  界面构成
   常见的GUI界面包含五个部分:主界面(main window), 菜单页面(menu), 按键(button), 标签(labels), 文本输入(text entry)	 
         wx.Frame(对应主界面)、
		 wx.MenuBar()(对应菜单类)、
		 wx.Button(对应按键)、
		 wx.StaticText(对应label)、
		 wx.TextCtrl(对应text entry)、
		 wx.lib.plot.PlotCanvas(对应画布)
	一个Frame可以包含多个 Panel ,Panel 里面可以包含label、text、plot,但是一个Frame只能有一个 Menu !
	   wx.Panel
       wx.Dialog, ,Dialog可以包含多个Panel,常用来实现选项界面

  界面布局。界面布局用到的类为wx.BoxSizer和wx.FlexGridSizer	
       wx.FlexGridSizer为一个经常使用的将多个部件 规则布局的

 事件绑定: 事件绑定也就是将组件和事件联系起来 绑定函数为Bind	

 多线程时使用 threading模块	 

Gooey

  Gooey decorator.
       18 different translations
       widget="TextField"
  Layout Customization
    Gooey 的国际化是通过配置实现的
    Menu Bar: AboutDialog MessageDialog  HtmlDialog Link
	  
     a progress bar status
    chooser 类控件有:
    控件名                控件类型
    FileChooser           文件选择器
    MultiFileChooser      文件多选器
    DirChooser            目录选择器
    MultiDirChooser       目录多选器
    FileSaver             文件保存
    DateChooser           日期选择
    TextField             文本输入框
    Dropdown              下拉列表
    Counter                计数器
    CheckBox               复选框
    RadioGroup             单选框
    Textarea               富文本

参考

https://www.wxpython.org/	 
Python的tkinter和pyinstaller打造易用的工具  https://www.cnblogs.com/ytwang/p/15111997.html    
python3 + Gooey快速开发GUI应用程序 https://blog.csdn.net/qq_33682575/article/details/103584885  
https://pakstech.com/blog/python-gooey/
https://gooey.readthedocs.io/en/latest/index.html
https://chriskiehl.com/article/packaging-gooey-with-pyinstaller
https://jackmckew.dev/making-executable-guis-with-python-gooey-pyinstaller.html
posted @ 2023-04-28 23:47  辰令  阅读(363)  评论(0编辑  收藏  举报