Example tutorials for GUI programs that use Wxpython and py2exe to develop Python in Windows _python

Source: Internet
Author: User
Tags md5 python script in python

Python supports visual programming, which is writing GUI programs that you can use to write your favorite desktop programs. Using Wxpython to do the interface is very simple, just can't drag the control like C #, need to write code layout. After writing, because the direct py file can no longer be installed on the Python computer to run, whether there is a packaged in any computer can run a tool, the Internet to find found Py2exe just can complete this function. Wxpython and Py2exe are open source free software.

Environment configuration
Wxpython:sourceforge project page https://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/
After downloading, double-click the installation, install the program will automatically install to the corresponding python\scripts.
Py2exe: Official Download homepage https://www.wxpython.org/download.php
Also double-click to install, note download the Python version to use.
The following examples illustrate the simple use of Wxpython and Py2exe.

Basic example
file name: wxtest.py:

#-*-coding:cp936-*-' MainWindow class completes the simplest editing function by adding a main menu, two submenus (about and exit) ' Import WX class MainWindow (WX. Frame): ' Define a window class ' Def __init__ (self, Parent, title): WX. Frame.__init__ (self, parent, title=title, size=) 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 of program ') menubar. Append (Menufile, ' &file ') #事件绑定 self. Bind (WX. Evt_menu, Self.onabout, mnuabout) self. Bind (WX. Evt_menu, Self.onexit, mnuexit) self. Setmenubar (menubar) def onabout (self, evt): "Click on the event response" "DLG = wx. Messagedialog (self, ' this app was a simple-text editor ', ' about my app ', WX. OK) dlg. ShowModal () dlg. Destroy () def onExit (self, evt): ' Click ' exit ' self. Close (True) app= WX. App (False) frame = MainWindow (None, ' Small Editor ') app.
 Mainloop () #循环监听事件

After editing the file, use Py2exe to compile the Python script into a Windows executable file, so you don't need the Python interpreter. To use Py2exe, you first write a compilation script, and then run the compilation script in Python to compile the other script into an executable file. The following instance is the script that will be compiled into an executable file, file name: setup.py

Import distutils
import py2exe
distutils.core.setup (windows=[' wxtest.py ')

In setup.py, there is only one statement in addition to importing the required modules:

Distutils.core.setup (windows=[' wxtest.py ')

In square brackets is the name of the script to compile, and windows at the front indicates that it is compiled into a GUI program. If you want to compile the executable file for the command-line interface, you can use the service option if you want to compile the script into a Windows service, as long as you change Windows to console.
After editing, wxtest.py and setup.py are placed under the same path, CMD enters the path, and enters:

setup.py Py2exe

If the following error occurred in the Run Times:
Error:MSVCP90.dll:No such file or directory
Because you didn't find MSVCP90.dll, search the MSVCP90.dll file in the Windows directory, and then copy it to DLLs under the Python installation directory.
When you package a PYQT project, you may report the following error
Importerror:no module named SIP
At this point only need to add--includes sip on the package, such as:
setup.py py2exe--includes SIP

After the run is completed, Dist and build two directories are generated under the path. The dist directory is the file that compiles the build. If you want to run a compiled program on other machines that do not have Python installed, simply copy the dist directory to another machine. Double-click to run WxTest.exe, as shown in figure:

Using Wxpython to build a MD5 GUI tool for computing files
Gadgets end up like this, dragging a file to it automatically calculates its MD5 and size

Here's the whole code.

#coding: GBK import wx import optparse import time,hashlib import threading import os def checkMD5 (pefile): try:f
  = Open (Pefile, ' RB ') data = F.read () m = Hashlib.md5 () m.update (data) f.close () return m.hexdigest ()
  Except:return ' ERROR ' def getfilesize (filename): try:size = Int (os.path.getsize (filename)) return size Except:return ' ERROR ' #线程函数 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 s

  elf.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.finished def dointhread (func, *params, **PARAMMAP): T_setdaemon = None if ' T_setdaemon ' in Parammap:t_setdaemon = parammap[' T_setdaemon '] del param map[' t_sEtdaemon '] ft = Functhread (func, *params, **parammap) if T_setdaemon!= None:ft.setDaemon (T_setdaemon) Ft.start () Return FT class Filedroptarget (WX. Filedroptarget): Def __init__ (self, filetext,md5tx,filesizetx): WX. Filedroptarget.__init__ (self) self.filepath = Filetext Self.md5tx = Md5tx Self.filesizetx = Filesizetx D EF Ondropfiles (self, x, Y, fileNames): filename = Filenames[0].encode (' GBK ') Print filename print type (filenam e) self.filepath.SetValue (filename) MD5 = Dointhread (checkmd5,filename) filesize = Dointhread (getfilesize,file Name) while True:if not md5.isfinished (): Time.sleep (0.5) Else:self.md5tx.SetValue (MD5.G 
        Etresult ()) break while True:if not filesize.isfinished (): time.sleep (0.5) Else: Self.filesizetx.SetValue (str (Filesize.getresult ())) Break class Frame (WX. Frame): #Frame 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. All around the distance, expand expands to all filepath = WX. Statictext (Self.panel,-1, "filedir (drag 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): # #继承wx. App def OnInit (self): # #还没有调起来的时候读取初始化 Self.frame = FRAME (' md5&size info ') self.frame.Centre () Self.fra Me. Show (True) return True def killself (evt = None): Os.system (' taskkill/f/t/pid%d >nul 2>nul '% Win32pro Cess. 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 notation, in the class app has a Def OnInit method to initialize the main frame, center it and show () out, nothing to say, mainly look at the definition of frame

This gadget uses Boxsizer to lay out, for simplicity I use only one boxsizer, all the controls inside are vertical (vertical) layout, if you want to put MD5 with the following text box on the same line, Then you need to add a level of Boxsizer, and then put this level of boxsizer into the main boxsizer

Boxsizer = wx. Boxsizer (WX. VERTICAL) #初始化一个垂直的boxSizer, is also the entire framework of the main sizer

Self.panel = wx. Panel (self) #初始化一个panel, this panel is the

filepath = WX of the controls that were put in place. Statictext (Self.panel,-1, "filedir (drag 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))



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, in fact, you can not use a panel, but it directly into the Boxsizer
 
 

Add filepath to the Boxsizer of the Lord, where I had some confusion at first, I thought first of all the controls into the panel, and then put the panel into the Boxsizer, but this is wrong, but should be directly into the Boxsizer , set the parent class of the control to a panel, and then do not put the panel into the Boxsizer step, WX. Left|wx. top,border=10 This parameter indicates that the control is 10 pixels away from the left and uses WX. Expand to make it fully populated its area, I once thought, can be set to distance 10px, left 20px, but seemingly can not be set, the Add function can only have a border parameter, in other words can only set the same number, and then I find out whether it can be achieved.

Boxsizer.add (( -1,20)) #这个是添加一个空距离, distance up to 20px

droptarget = Filedroptarget (filetext,md5tx,filesizetx) 
Self.panel.SetDropTarget (DropTarget)

This is the window class to add a drag method, but also a more fixed way of writing

The __init__ and Ondropfiles methods in the class Filedroptarget above are also fixed methods, except that the processing functions are different.

Some of the style and flag in the Wxpython in the layout of the use of some experience, there are many of its controls and the method of binding, to master the need for a few more time, the following two sites are introduced more detailed, more access

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.