Wxpython Study Notes (recommended)

Source: Internet
Author: User
Tags glob wxwidgets
WxPython is a GUI toolbox in the Python programming language. He allows Python programmers to easily create programs with robust and powerful graphical user interfaces. 1. Introduction

WxPython is a GUI toolbox in the Python programming language. He enables Python programmers to easily create programs with robust and powerful graphical user interfaces. It is used by the Python language to bind the popular wxWidgets cross-platform GUI tool library. WxWidgets is written in C ++. Like the Python language and the wxWidgets GUI tool library, wxPython is an open source software. This means that anyone can use it for free, view and modify its source code, or contribute patches to add features. WxPython is cross-platform. This means that the same program can run on multiple platforms without modification. Currently, the supported platforms include 32-bit Microsoft Windows OS, most Unix or Unix-like systems, and Apple Mac OS X. Because Python is used as a programming language, wxPython is easy to write and understand.

Ii. Basic use

If it is basically used, it is very detailed at this address. I do not need to repeat it again:

Http://wiki.wxpython.org/Getting%20Started

3. common controls
1. menu)

Http://wiki.wxpython.org/Getting%20Started#head-33e6dc36df2a89db146142e9a97b6e36b956875f

2. Page Layout (Sizer)

This is troublesome to use. refer to the following page:

Http://wiki.wxpython.org/Getting%20Started#head-7455553d71be4fad208480dffd53b7c68da1a982

Detailed explanation of the layout of wxPython frame (1)

WxPython frame layout (2)

3. Tab page (notebook)

Http://wiki.wxpython.org/Getting%20Started#head-b20d2fc488722cdb3f6193150293d1e118734db8

4. List Control (ListCtrl)

This control is relatively powerful and is one of my favorite controls. In Chapter 13th of wxPythonInAction, I will introduce it. (If you want an electronic version of the book and the accompanying source code, ask me)

The following is a simple usage in list_report.py:

The Code is as follows:


Import wx
Import sys, glob, random
Import data

Class DemoFrame (wx. Frame ):
Def _ init _ (self ):
Wx. Frame. _ init _ (self, None,-1,
"Wx. ListCtrl in wx. LC_REPORT mode ",
Size = (600,400 ))

Il = wx. ImageList (16, 16, True)
For name in glob. glob ("smicon ??. Png "):
Bmp = wx. Bitmap (name, wx. BITMAP_TYPE_PNG)
Il_max = il. Add (bmp)
Self. list = wx. ListCtrl (self,-1, style = wx. LC_REPORT)
Self. list. AssignImageList (il, wx. IMAGE_LIST_SMALL)

# Add some columns
For col, text in enumerate (data. columns ):
Self. list. InsertColumn (col, text)

# Add the rows
For item in data. rows:
Index = self. list. InsertStringItem (sys. maxint, item [0])
For col, text in enumerate (item [1:]):
Self. list. SetStringItem (index, col + 1, text)

# Give each item a random image
Img = random. randint (0, il_max)
Self. list. SetItemImage (index, img, img)

# Set the width of the columns in various ways
Self. list. SetColumnWidth (0,120)
Self. list. SetColumnWidth (1, wx. LIST_AUTOSIZE)
Self. list. SetColumnWidth (2, wx. LIST_AUTOSIZE)
Self. list. SetColumnWidth (3, wx. LIST_AUTOSIZE_USEHEADER)


App = wx. PySimpleApp ()
Frame = DemoFrame ()
Frame. Show ()
App. MainLoop ()

For the ListCtrl control, I want to add the following:

1. How to obtain the selected project?

The most common method is to obtain the first selected Item: GetFirstSelected (). This function returns an int, that is, the ID of the Item in ListCtrl.

Another method is GetNextSelected (itemid). After obtaining the specified itemid, the first selected item is returned.

Through these two methods, we can traverse all the selected items:

The Code is as follows:


GetNextSelecteditemid = self. list. GetFirstSelected ()
While itemid <>-1:
# Do something
Itemid = self. list. GetNextSelected (itemid)

If you want to obtain the value of a row and column, use the following method:

The Code is as follows:


# Obtain the values of 0th rows and 1st Columns
Itemtext = self. list. GetItem (0, 1). Text

2. How do I add a right-click menu after the selected item?

In the _ init _ function, add the following event binding:
Self. list. Bind (wx. EVT_CONTEXT_MENU, self. OnContextMenu) and then add the OnContextMenu method:

The Code is as follows:


Def OnContextMenu (self, event ):
If not hasattr (self, "popupStop "):
Self. popupStop = wx. NewId ()
Self. popupPropery = wx. NewId ()
Self. Bind (wx. EVT_MENU, self. OnPopupStop, id = self. popupStop)
Self. Bind (wx. EVT_MENU, self. OnPopupProperty, id = self. popupPropery)

# Create a menu
Menu = wx. Menu ()
ItemStop = wx. MenuItem (menu, self. popupStop, "Stop ")
ItemProperty = wx. MenuItem (menu, self. popupPropery, 'properties ')

Menu. AppendItem (itemStop)
Menu. AppendItem (itemProperty)

ItemProperty. Enable (False) # The property button is invalid by default.

If itemid =-1: # if no item is selected
ItemStop. Enable (False)
Else:
ItemStop. Enable (False)
ItemProperty. Enable (True)
# The menu is displayed only here.
Self. PopupMenu (menu)
# Finally, destroy the previously created menu
Menu. Destroy ()

5. Select File Dialog Box (FileDialog)

Easy to use:

The Code is as follows:


Dlg = wx. FileDialog (self,
Message = "Yes, select a place ",
Wildcard = "PNG (*. png) | *. png ",
Style = wx. SAVE
)
Savefile =''
If dlg. ShowModal () = wx. ID_ OK:
Savefile = dlg. GetPath ()
Try:
OS. remove (self. filename)
Except t:
Pass
Self. img. SaveFile (savefile, wx. BITMAP_TYPE_PNG)
Self. filename = savefile
Dlg. Destroy ()

6. Select folder dialog box (DirDialog)

The Code is as follows:


Dialog = wx. DirDialog (None, 'Choose a directory :',
Style = wx. DD_DEFAULT_STYLE | wx. DD_NEW_DIR_BUTTON)
If dialog. ShowModal () = wx. ID_ OK:
For itemid in range (self. list. GetItemCount ()):
Self. savechart (itemid, graphpath)
Dialog. Destroy ()

4. Tips

1. Set the shortcut key

For example, if you want to press F5 to execute an operation, you can use the following method in the _ init _ function:

The Code is as follows:


Acceltbl = wx. AcceleratorTable ([(wx. ACCEL_NORMAL, wx. WXK_F5, self. btnrun. GetId ()])
Self. SetAcceleratorTable (acceltbl)

Another common case is to press ESC to close the window. We know that there is a very simple way to use the SetId (wx. ID_CANCEL) method, such:

The Code is as follows:


Self. btncancel = wx. Button (self. panel1,-1, 'cancel', wx. Point (380,280 ))
Self. btncancel. SetId (wx. ID_CANCEL)

In this way, when you press the ESC key, the current Dialog will be closed. Note! Here is the Dialog, that is, the window object inherited from wx. Dialog. It does not seem effective for wx. Frame to use SetId.

2. Use the timer
The following is an example in Chapter 18 of wxPythonInAction:

The Code is as follows:


Import wx
Import time

Class ClockWindow (wx. Window ):
Def _ init _ (self, parent ):
Wx. Window. _ init _ (self, parent)
Self. Bind (wx. EVT_PAINT, self. OnPaint)
Self. timer = wx. Timer (self)
Self. Bind (wx. EVT_TIMER, self. OnTimer, self. timer)
Self. timer. Start (1000)

Def Draw (self, dc ):
T = time. localtime (time. time ())
St = time. strftime ("% I: % M: % S", t)
W, h = self. GetClientSize ()
Dc. SetBackground (wx. Brush (self. GetBackgroundColour ()))
Dc. Clear ()
Dc. SetFont (wx. Font (30, wx. SWISS, wx. NORMAL, wx. NORMAL ))
Tw, th = dc. GetTextExtent (st)
Dc. DrawText (st, (w-tw)/2, (h)/2-th/2)

Def OnTimer (self, evt ):
Dc = wx. BufferedDC (wx. ClientDC (self ))
Self. Draw (dc)

Def OnPaint (self, evt ):
Dc = wx. BufferedPaintDC (self)
Self. Draw (dc)

Class MyFrame (wx. Frame ):
Def _ init _ (self ):
Wx. Frame. _ init _ (self, None, title = "wx. Timer ")
ClockWindow (self)

App = wx. PySimpleApp ()
Frm = MyFrame ()
Frm. Show ()
App. MainLoop ()

3. What you must know when multithreading is used: wx. CallAfter

In wxpython, note that wx. CallAfter must be used to notify the window object Update Status in the thread. Example in Chapter 18:

The Code is as follows:


Import wx
Import threading
Import random

Class WorkerThread (threading. Thread ):
"""
This just simulates some long-running task that periodically sends
A message to the GUI thread.
"""
Def _ init _ (self, threadNum, window ):
Threading. Thread. _ init _ (self)
Self. threadNum = threadNum
Self. window = window
Self. timeToQuit = threading. Event ()
Self. timeToQuit. clear ()
Self. messageCount = random. randint (10, 20)
Self. messageDelay = 0.1 + 2.0 * random. random ()

Def stop (self ):
Self. timeToQuit. set ()

Def run (self ):
Msg = "Thread % d iterating % d times with a delay of % 1.4f \ n "\
% (Self. threadNum, self. messageCount, self. messageDelay)
Wx. CallAfter (self. window. LogMessage, msg)

For I in range (1, self. messageCount + 1 ):
Self. timeToQuit. wait (self. messageDelay)
If self. timeToQuit. isSet ():
Break
Msg = "Message % d from thread % d \ n" % (I, self. threadNum)
Wx. CallAfter (self. window. LogMessage, msg)
Else:
Wx. CallAfter (self. window. ThreadFinished, self)

Class MyFrame (wx. Frame ):
Def _ init _ (self ):
Wx. Frame. _ init _ (self, None, title = "Multi-threaded GUI ")
Self. threads = []
Self. count = 0

Panel = wx. Panel (self)
StartBtn = wx. Button (panel,-1, "Start a thread ")
StopBtn = wx. Button (panel,-1, "Stop all threads ")
Self. tc = wx. StaticText (panel,-1, "Worker Threads: 00 ")
Self. log = wx. TextCtrl (panel,-1 ,"",
Style = wx. TE_RICH | wx. TE_MULTILINE)

Inner = wx. BoxSizer (wx. HORIZONTAL)
Inner. Add (startBtn, 0, wx. RIGHT, 15)
Inner. Add (stopBtn, 0, wx. RIGHT, 15)
Inner. Add (self. tc, 0, wx. ALIGN_CENTER_VERTICAL)
Main = wx. BoxSizer (wx. VERTICAL)
Main. Add (inner, 0, wx. ALL, 5)
Main. Add (self. log, 1, wx. EXPAND | wx. ALL, 5)
Panel. SetSizer (main)

Self. Bind (wx. EVT_BUTTON, self. OnStartButton, startBtn)
Self. Bind (wx. EVT_BUTTON, self. OnStopButton, stopBtn)
Self. Bind (wx. EVT_CLOSE, self. OnCloseWindow)

Self. UpdateCount ()

Def OnStartButton (self, evt ):
Self. count + = 1
Thread = WorkerThread (self. count, self)
Self. threads. append (thread)
Self. UpdateCount ()
Thread. start ()

Def OnStopButton (self, evt ):
Self. StopThreads ()
Self. UpdateCount ()

Def OnCloseWindow (self, evt ):
Self. StopThreads ()
Self. Destroy ()

Def StopThreads (self ):
While self. threads:
Thread = self. threads [0]
Thread. stop ()
Self. threads. remove (thread)

Def UpdateCount (self ):
Self. tc. SetLabel ("Worker Threads: % d" % len (self. threads ))

Def LogMessage (self, msg ):
Self. log. AppendText (msg)

Def ThreadFinished (self, thread ):
Self. threads. remove (thread)
Self. UpdateCount ()

App = wx. PySimpleApp ()
Frm = MyFrame ()
Frm. Show ()
App. MainLoop ()

4. Do I need to start another GUI program in the program without losing the focus of the main window?
Generally, it is okay to call OS. popen to run other external programs. However, in wxpython, wx will lose its current focus, even if the program to be opened becomes a mode dialog box. To solve this problem, use the wx. Execute method.

The Code is as follows:


Wx. Execute ('notepad ')

5. Learning Resources

1. http://wiki.wxpython.org/FrontPage official

2. woodpecker WIKI: http://wiki.woodpecker.org.cn/moin/WxPythonInAction

Author: CoderZh (CoderZh)
Source: http://coderzh.cnblogs.com

Related Article

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.