Python 3学习笔记(18):图形化GUI编程Wx文件编辑

  • 运行效果

Python 3学习笔记(18):图形化GUI编程Wx文件编辑_第1张图片

  • Python图形化模块介绍

1、Tkinter :是python最简单的图形化模块, Tkinter 模块(Tk 接口)是 Python 的标准 Tk GUI 工具包的接口 。总共只有15种组件

2、Pyqt:是python最复杂也是使用最广泛的图形化

3、Wx:是python当中居中的一个图形化,学习结构很清晰

4、Pywin   :是python windows 下的模块,摄像头控制(opencv),常用于外挂制作

5、Jython:Jython 程序可以和 Java 无缝集成。除了一些标准模块,Jython 使用 Java 的模块。Jython 几乎拥有标准的Python 中不依赖于 C 语言的全部模块。比如,Jython 的用户界面将使用 Swing,AWT或者 SWT。Jython 可以被动态或静态地编译成 Java 字节码。

  • wx模块的安装:

C:\Users\Administrator>pip install wxpython

检验已安装的包:    python -m pip list

  • wxFormBuilder的安装:

下载地址:wxFormBuilder_v3.9.0.exe

https://github.com/wxFormBuilder/wxFormBuilder/releases

  • 图形化介绍

使用可视化的界面设计工具wxFormBuilder创建一个漂亮的图形用户界面,选择Python作为代码生成语言,保存项目,然后按F8键生成 Python代码开发的GUI。让生成的文件命名为wxFrame25.py

  • 声明Application对象并添加事件处理程序

声明Application对象并启动主事件循环。添加事件处理程序。

# -*- coding: utf-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version Oct 26 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################

import wx
import wx.xrc
import os.path

wx.ID_Open = 1000
wx.ID_Save = 1001
wx.ID_SaveAs = 1002
wx.ID_Exit = 1003
wx.ID_About1 = 1004

###########################################################################
## Class MyFrame1
###########################################################################

class MyFrame1 ( wx.Frame ):

	def __init__( self, parent ):
		wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"文件编辑", pos = wx.DefaultPosition, size = wx.Size( 728,457 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )

		self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )

		self.m_statusBar1 = self.CreateStatusBar( 1, wx.STB_SIZEGRIP, wx.ID_ANY )
		self.m_toolBar1 = self.CreateToolBar( wx.TB_HORIZONTAL, wx.ID_ANY )
		pic=wx.Image(u"OUTOPEN.BMP",wx.BITMAP_TYPE_BMP).ConvertToBitmap()  #载入bmp图片
		self.m_bpButton1 = wx.BitmapButton( self.m_toolBar1, -1, pic, pos=(1,1))

		self.m_toolBar1.AddControl( self.m_bpButton1 )
		pic2=wx.Image(u"saveall.BMP",wx.BITMAP_TYPE_BMP).ConvertToBitmap()  

		self.m_bpButton2 = wx.BitmapButton( self.m_toolBar1, -1, pic2, pos=(1,21))
		self.m_toolBar1.AddControl( self.m_bpButton2 )
		self.m_bpButton3 = wx.BitmapButton( self.m_toolBar1, -1, pic2, pos=(1,41))
		self.m_toolBar1.AddControl( self.m_bpButton3 )
		pic3=wx.Image(u"OUTCLOSE.BMP",wx.BITMAP_TYPE_BMP).ConvertToBitmap() 
		
		self.m_bpButton4 = wx.BitmapButton( self.m_toolBar1, -1, pic3, pos=(1,41))
		self.m_toolBar1.AddControl( self.m_bpButton4 )
		self.m_bpButton5 = wx.BitmapButton( self.m_toolBar1, wx.ID_ANY, wx.NullBitmap, wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW|0 )
		self.m_toolBar1.AddControl( self.m_bpButton5 )
		self.m_toolBar1.Realize()

		self.m_menubar1 = wx.MenuBar( 0 )
		self.m_File = wx.Menu()
		self.m_Open = wx.MenuItem( self.m_File, wx.ID_Open, u"打开", wx.EmptyString, wx.ITEM_NORMAL )
		self.m_File.Append( self.m_Open )

		self.m_Save = wx.MenuItem( self.m_File, wx.ID_Save, u"保存", wx.EmptyString, wx.ITEM_NORMAL )
		self.m_File.Append( self.m_Save )

		self.m_SaveAs = wx.MenuItem( self.m_File, wx.ID_SaveAs, u"另存", wx.EmptyString, wx.ITEM_NORMAL )
		self.m_File.Append( self.m_SaveAs )

		self.m_File.AppendSeparator()

		self.m_Exit = wx.MenuItem( self.m_File, wx.ID_Exit, u"退出", wx.EmptyString, wx.ITEM_NORMAL )
		self.m_File.Append( self.m_Exit )

		self.m_menubar1.Append( self.m_File, u"文件" )

		self.m_About = wx.Menu()
		self.m_About1 = wx.MenuItem( self.m_About, wx.ID_About1, u"关于...", wx.EmptyString, wx.ITEM_NORMAL )
		self.m_About.Append( self.m_About1 )

		self.m_menubar1.Append( self.m_About, u"关于" )

		self.SetMenuBar( self.m_menubar1 )

		bSizer1 = wx.BoxSizer( wx.VERTICAL )

		self.m_Text1 =  wx.TextCtrl(self, style=wx.TE_MULTILINE)
		bSizer1.Add( self.m_Text1, 1, wx.EXPAND |wx.ALL, 5 )

		self.SetSizer( bSizer1 )
		self.Layout()

		self.Centre( wx.BOTH )

		# Connect Events
		self.m_bpButton1.Bind( wx.EVT_BUTTON, self.m_OpenClick )
		self.m_bpButton2.Bind( wx.EVT_BUTTON, self.m_SaveClick )
		self.m_bpButton3.Bind( wx.EVT_BUTTON, self.m_SaveAsClick )
		self.m_bpButton4.Bind( wx.EVT_BUTTON, self.m_ExitClick )
		self.m_bpButton5.Bind( wx.EVT_BUTTON, self.m_About1Click )
		self.Bind( wx.EVT_MENU, self.m_OpenClick, id = self.m_Open.GetId() )
		self.Bind( wx.EVT_MENU, self.m_SaveClick, id = self.m_Save.GetId() )
		self.Bind( wx.EVT_MENU, self.m_SaveAsClick, id = self.m_SaveAs.GetId() )
		self.Bind( wx.EVT_MENU, self.m_ExitClick, id = self.m_Exit.GetId() )
		self.Bind( wx.EVT_MENU, self.m_About1Click, id = self.m_About1.GetId() )

	def __del__( self ):
		pass


	# Virtual event handlers, overide them in your derived class
	def m_OpenClick( self, event ):
		pass

	def m_SaveClick( self, event ):
		pass

	def m_SaveAsClick( self, event ):
		pass
		
	def m_ExitClick( self, event ):
		pass

	def m_About1Click( self, event ):
		pass


class MainWindow(MyFrame1):
	def __init__(self,parent,filename='noname.txt'):
		self.filename = filename
		self.dirname = '.'
		MyFrame1.__init__(self,parent)

	def SetTitle(self):
        # MainWindow.SetTitle overrides wx.Frame.SetTitle, so we have to
        # call it using super:
		super(MainWindow, self).SetTitle('Editor %s'%self.filename)
		

	def defaultFileDialogOptions(self):
		''' Return a dictionary with file dialog options that can be
			used in both the save file dialog as well as in the open
			file dialog. '''
		return dict(message='Choose a file', defaultDir=self.dirname,wildcard='*.*')

	def askUserForFilename(self, **dialogOptions):
		dialog = wx.FileDialog(self, **dialogOptions)
		if dialog.ShowModal() == wx.ID_OK:
			userProvidedFilename = True
			self.filename = dialog.GetFilename()
			self.dirname = dialog.GetDirectory()
			self.SetTitle() # Update the window title with the new filename
		else:
			userProvidedFilename = False
		dialog.Destroy()
		return userProvidedFilename

	def m_About1Click( self, event ):
		dialog=wx.MessageDialog(self,'A sample editor in wxPython','About Sample Editor',wx.OK)
		dialog.ShowModal()
		dialog.Destroy()
		
	def m_ExitClick( self, event ):
		self.Close()

	def m_OpenClick( self, event ):
		if self.askUserForFilename(style=wx.FD_OPEN,**self.defaultFileDialogOptions()):
			textfile = open(os.path.join(self.dirname, self.filename), 'r',encoding='iso-8859-1')    
			data=textfile.read()
			data=data.encode('iso-8859-1').decode('utf-8')
			self.m_Text1.SetValue(data)
			textfile.close()

	def m_SaveClick( self, event ):
		textfile = open(os.path.join(self.dirname, self.filename), 'w', encoding= 'utf-8')
		textfile.write(self.m_Text1.GetValue())
		textfile.close()
       
	def m_SaveAsClick(self, event):
		if self.askUserForFilename(style=wx.FD_SAVE,**self.defaultFileDialogOptions()):
			self.m_SaveClick(event)
       
if __name__ == '__main__':
    app = wx.App() 
    main_win = MainWindow(None)
    main_win.Show()
    app.MainLoop()



 

  • wxFileDialog类对象说明

wx.FileDialog定义风格参数:

S.N.

参数和说明

1

wx.FD_DEFAULT_STYLE

相当于wxFD_OPEN

2

wx.FD_OPEN

这是一个打开的对话框;该对话框的默认按钮的标签是打开

3

wx.FD_SAVE

这是一个保存对话框;该对话框的默认按钮的标签是保存

4

wx.FD_OVERWRITE_PROMPT

对于只保存对话框:提示进行确认,如果一个文件将被覆盖

5

wx.FD_MULTIPLE

仅适用于打开的对话框:允许选择多个文件

6

wx.FD_CHANGE_DIR

更改当前工作目录到用户选择的文件是目录

wx.FileDialog类的成员函数

S.N.

参数和说明

1

GetDirectory()

返回默认目录

2

GetFileName()

返回默认文件名

3

GetPath()

返回选定文件的完整路径

4

SetDirectory()

设置默认目录

5

SetFilename()

设置默认文件

6

SetPath()

设置文件路径

7

ShowModal()

显示对话框,如果用户单击OK按钮返回wx.ID_OK,否则 wx.ID_CANCEL

 

  • 非法字符的转换

读文件,报非法字符(去stackoverflow看),先编码成iso-8859-1再转utf-8。

textfile = open(os.path.join(self.dirname, self.filename), 'r',encoding='iso-8859-1')   

data=textfile.read()

data=data.encode('iso-8859-1').decode('utf-8')

  • 打包生成EXE文件

安装pyinstaller (C:\Users\Administrator>pip install pyinstaller),打包执行:

pyinstaller -F -w tools2.py

或pyinstaller -F tools2.py –noconsole

 

你可能感兴趣的:(Python)