How to use wxPython and py2exe to develop Python GUI programs in Windows

Source: Internet
Author: User
WxPython is a graphical class library tool integrated with Python, and py2exe is a program that converts a Python program to an executable file of exe, the combination of the two allows you to easily create graphical programs in Windows. here we will learn how to use wxPython and py2exe to develop Python GUI programs in Windows. Tutorial: Python supports Visual programming, you can use it to write your favorite desktop programs. Using wxPython is very simple, but you cannot drag controls like C #. you need to write your own code layout. After writing the file, you cannot run the file directly on a python computer. can you package it into a tool that can run on any computer, you can find py2exe on the Internet to complete this function. WxPython and py2exe are both open-source free software.

Environment configuration
WxPython: sourceforge project page https://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/
Download the package and double-click it to install it. the installer is automatically installed under the corresponding python \ Scripts.
Py2exe: Official Download home https://www.wxpython.org/download.php
You can also double-click it to install it. Be sure to download the corresponding Python version.
The following examples illustrate the simple use of wxPython and py2exe respectively.

Basic example
File name: wxTest. py:

#-*-Coding: cp936-*-''' MainWindow class to complete the simplest editing function. add a main menu and two sub-menus (about and exit) '''import wx class MainWindow (wx. frame): ''' defines a window class ''' def _ init _ (self, parent, title): wx. frame. _ init _ (self, parent, title = title, size = (300,300) self. control = wx. textCtrl (self, style = wx. TE_MULTILINE) self. setupMenuBar () self. show (True) def setupMenuBar (self): self. createStatusBar () menubar = wx. menuBar () menufile = wx. menu () mnuabout = menufile. append (wx. ID_ABOUT, '& about', 'About this shit') mnuexit = menufile. append (wx. ID_EXIT, 'e & xit', 'end program ') menubar. append (menufile, '& file') # bind events to self. bind (wx. EVT_MENU, self. onAbout, mnuabout) self. bind (wx. EVT_MENU, self. onExit, mnuexit) self. setMenuBar (menubar) def onAbout (self, evt): ''' click the event response of about ''' dlg = wx. messageDialog (self, 'This app is a simple text editor', 'about my app', wx. OK) dlg. showModal () dlg. destroy () def onExit (self, evt): ''' click to exit ''' self. close (True) app = wx. app (False) frame = MainWindow (None, 'small editor') app. mainLoop () # loop listening event

After editing the file, use py2exe to compile the Python script into a Windows executable file, so that you do not need the Python interpreter. To use py2exe, you must first compile a compilation script, and then run the compilation script in Python to compile other scripts into executable files. The following example shows the script to be compiled into an executable file. the file name is setup. py.

import distutilsimport py2exedistutils.core.setup(windows=['wxTest.py'])

In setup. py, apart from importing required modules, there is only one statement:

distutils.core.setup(windows=['wxTest.py'])

The name of the script to be compiled is in square brackets. the front windows indicates that the script is compiled into a GUI program. To compile the executable file on the command line interface, you only need to change windows to the console. if you need to compile the script into a Windows service, you can use the service option.
After editing, place wxTest. py and setup. py in the same path. cmd enter this path and enter:

setup.py py2exe

If the following error is reported during running:

error: MSVCP90.dll: No such file or directory

Because MSVCP90.dll is not found, search for the MSVCP90.dll file in the windows directory and copy it to the DLLs directory in the python installation directory.
When packaging a PyQt project, the following error may be reported:

ImportError: No module named sip

In this case, you only need to add -- includes sip to the package, such:

setup.py py2exe --includes sip

After running, The dist and build directories are generated in the path. The dist directory contains the compiled files. If you want to run the compiled program on another machine without Python installed, just copy the dist directory to another machine. Run wxtest.exe in double-click mode ,:

Use wxPython to create a GUI tool for calculating file md5
The following figure shows the final state of the small tool. dragging the file above will automatically calculate its md5 and size.

Below is all the code

# Coding: gbkimport wximport optparseimport time, hashlibimport threadingimport osdef checkMD5 (pefile): try: f = open (pefile, 'RB') data = f. read () m = hashlib. md5 () m. update (data) f. close () return m. hexdigest () handle T: return 'error' def getFileSize (filename): try: size = int (OS. path. getsize (filename) return size failed t: return 'error' # thread function class FuncThread (threading. thread): def _ init _ (self, func, * Params, ** paramMap): threading. thread. _ init _ (self) self. func = func self. params = params self. paramMap = paramMap self. rst = None self. finished = False def run (self): self. rst = self. func (* self. params, ** self. paramMap) self. finished = True def getResult (self): return self. rst def isFinished (self): return self. finisheddef doInThread (func, * params, ** paramMap): t_setDaemon = None if 't_ setDaemon 'In paramMap: t_setDaemon = paramMap ['t _ setDaemon '] del paramMap ['t _ setDaemon'] ft = FuncThread (func, * params, ** paramMap) if t_setDaemon! = None: ft. setDaemon (t_setDaemon) ft. start () return ftclass FileDropTarget (wx. fileDropTarget): def _ init _ (self, filetext, md5tx, filesizetx): wx. fileDropTarget. _ init _ (self) self. filepath = filetext self. md5tx = md5tx self. filesizetx = filesizetx def OnDropFiles (self, x, y, fileNames): filename = fileNames [0]. encode ('gbk') print filename print type (filename) self. filepath. setValue (filename) md5 = doInThread (checkMD5, filename) filesize = doInThread (getFileSize, filename) while True: if not md5.isFinished (): time. sleep (0.5) else: self. md5tx. setValue (md5.getResult () break while True: if not filesize. isFinished (): time. sleep (0.5) else: self. filesizetx. setValue (str (filesize. getResult () breakclass Frame (wx. frame): # Frame to initialize def _ init _ (self, title): wx. frame. _ init _ (self, None, title = title, size = (400,300) boxSizer = wx. boxSizer (wx. VERTICAL) self. panel = wx. panel (self) # boxSizer. add (self. panel, 1, wx. EXPAND | wx. ALL) # wx. the distance around ALL, EXPAND expanded to ALL filepath = wx. staticText (self. panel,-1, "FileDir (drag the file to this dialog box)") filetext = wx. textCtrl (self. panel,-1, "", size = (350,20) md5st = wx. staticText (self. panel,-1, "MD5") md5tx = wx. textCtrl (self. panel,-1, size = (250,20) filesizest = wx. staticText (self. panel,-1, 'filesize') filesizetx = wx. textCtrl (self. panel,-1, size = (250,20) # hashst = wx. staticText (self. panel,-1, 'hash') # hashtx = wx. textCtrl (self. panel,-1, size = (250,20) boxSizer. add (filepath, 0, wx. EXPAND | wx. LEFT | wx. TOP, border = 10) boxSizer. add (filetext, 0, wx. LEFT | wx. TOP, border = 10) boxSizer. add (-1, 20) boxSizer. add (md5st, 0, wx. LEFT | wx. TOP, border = 10) boxSizer. add (md5tx, 0, wx. LEFT | wx. TOP, border = 10) boxSizer. add (-1, 10) boxSizer. add (filesizest, 0, wx. LEFT | wx. TOP, border = 10) boxSizer. add (filesizetx, 0, wx. LEFT | wx. TOP, border = 10) # boxSizer. add (-1, 10) # boxSizer. add (hashst, 0, wx. LEFT | wx. TOP, border = 10) # boxSizer. add (hashtx, 0, wx. LEFT | wx. TOP, border = 10) dropTarget = FileDropTarget (filetext, md5tx, filesizetx) self. panel. setDropTarget (dropTarget) self. panel. setSizer (boxSizer) class App (wx. app): # inherit wx. app def OnInit (self): # Read and initialize self when no call is made. frame = Frame ('md5 & size information') self. frame. centre () self. frame. show (True) return Truedef killSelf (evt = None): OS. system ('taskkill/F/T/PID % d> NUL 2> NUL '% win32process. getCurrentProcessId () if _ name _ = '_ main _': parser = optparse. optionParser () parser. add_option ('-X',' -- no-Update', dest = 'test', action = 'store _ true', help = 'start without update') parser. add_option ('-t',' -- no-update-test', dest = 'test2', action = 'store _ true', help = 'start without update debug ') options, args = parser. parse_args () if options. test: print ("-x param") if options. test2: print ("-t param") App (redirect = False ). mainLoop ()

A little explanation:

Class App and App (). mainLoop () is a fixed method. in the class App, there is a def OnInit method to initialize the main Frame, center it and Show () out. there is nothing to say, let's take a look at the definition of Frame.

This tool uses boxSizer for layout. for simplicity, I only use one boxSizer to layout all the controls in it in VERTICAL (VERTICAL) mode, if you want to put MD5 in the same line as the text box next to it, you need to add a horizontal boxSizer, and then place the horizontal boxSizer into the main boxSizer.

BoxSizer = wx. boxSizer (wx. VERTICAL) # initialize a VERTICAL boxSizer, which is also the main Sizerself of the entire framework. panel = wx. panel (self) # initialize a panel. this panel is the filepath = wx of the placed control. staticText (self. panel,-1, "FileDir (drag the file to this dialog box)") filetext = wx. textCtrl (self. panel,-1, "", size = (350,20) md5st = wx. staticText (self. panel,-1, "MD5") md5tx = wx. textCtrl (self. panel,-1, size = (250,20) filesizest = wx. staticText (self. panel,-1, 'filesize') filesizetx = wx. textCtrl (self. panel,-1, size = ))

The above is the initialization of the corresponding static text and text box, the first parameter in the method is its parent class window, here is self. panel, you can also directly put it into boxSizer instead of panel.

boxSizer.Add(filepath,0,wx.EXPAND|wx.LEFT|wx.TOP,border=10) 

Add filepath to the main boxSizer. at the beginning, I was confused. at first, I thought that I would first put all the controls into the panel, and then put the panel into the boxSizer, however, this is not correct. Instead, it should be directly imported to boxSizer. the parent class of the control is set to panel, and then the panel is not put into the boxSizer step. wx. LEFT | wx. the TOP, border = 10 parameter indicates that the control is 10 pixels away from the TOP left, and wx is used. EXPAND to make it fully fill the region where it is located. I used to wonder if it can be set to a distance of 10 px and 20 px left, but it seems that it cannot be set like this, the Add function can only have one border parameter. In other words, it can only set the same value. then I will try again to see if it can be implemented.

BoxSizer. Add (-) # Add an empty distance between 20 pxdropTarget = FileDropTarget (filetext, md5tx, filesizetx) self. panel. SetDropTarget (dropTarget)

This is to add a drag method to the window class, which is also relatively fixed.

The _ init _ and OnDropFiles methods in the above class FileDropTarget are also fixed, except that the processing functions are different.

Some style and flag parameters in wxPython require some experience in layout, as well as many controls and binding methods. to be familiar with them, you still need to work hard, the following two websites are described in detail.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.