Wxpython Study notes (recommended)

Source: Internet
Author: User
Tags glob wxwidgets

First, Introduction

Wxpython is a GUI toolbox for the Python programming language. He makes it easy for Python programmers to create programs with robust, powerful graphical user interfaces. It is the Python language's binding to the popular Wxwidgets cross-platform GUI ToolPak. And Wxwidgets is written in the C + + language. Like the Python language and the wxwidgets GUI tool library, Wxpython is open source software. This means that anyone can use it for free and can view and modify its source code, or contribute patches to add functionality. The Wxpython is cross-platform. This means that the same program can run on multiple platforms without modification. Today's supported platforms are: 32-bit Microsoft Windows operating system, most Unix or Unix-like systems, Apple Mac OS X. Because of the use of Python as a programming language, Wxpython is easy to write and easy to understand.

Second, basic use

Basic use of the words to this address is very detailed, I do not need to repeat it:

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

Iii. Common Controls

1. Menus (menu)

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

2. Page layout (Sizer)

This stuff is more troublesome to use, refer to the following page:

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

WxPython frame Layout explained in detail (i)

WxPython frame Layout explained in detail (ii)

3. tab page (notebook)

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

4. List control (Listctrl)

This control is more powerful and is one of the controls I prefer to use. In the "Wxpythoninaction" a book in the 13th chapter has introduced (want the book electronic version and the accompanying source of the friend can ask me to)

Here are the simple uses provided 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, the 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, the 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, there are several places I would like to add:

1. How do I get the selected item?

The most common method is to get the first item selected: Getfirstselected (), which returns an int, the ID of an item in Listctrl.

Another method is: getnextselected (itemid), gets the first selected item after the specified Itemid, and also returns Itemid.

With these two methods, we can iterate through 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 get the value of a column for a row, use the following method:

The code is as follows:


#获取第0行, the value of column 1th
Itemtext = Self.list.GetItem (0, 1). Text

2. How do I add a right-click menu after selecting an item?

In the __INIT__ function, add the following event bindings:
Self.list.Bind (WX. Evt_context_menu, self. OnContextMenu) 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, ' property ')

Menu. Appenditem (Itemstop)
Menu. Appenditem (ItemProperty)

Itemproperty.enable (False) #默认让属性按钮变成无效状态

if Itemid = =-1: #如果没有选中任何项
Itemstop.enable (False)
Else
Itemstop.enable (False)
Itemproperty.enable (True)
#到这里才弹出菜单
Self. PopupMenu (menu)
#最后注意销毁前面创建的菜单
Menu. Destroy ()

5. Select File dialog box (FileDialog)

Very simple 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
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 ()

Iv. Some skills

1. Set shortcut keys

For example, if you want to perform an action by F5, 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)

There is also a very common case, which is to press the ESC key to close the window. We know that there is a very simple way to use the SetID (Wx.id_cancel) method, such as:

The code is as follows:


Self.btncancel = wx. Button (Self.panel1,-1, ' Cancel ', WX. Point (380, 280))
Self.btncancel.SetId (Wx.id_cancel)

This way, when the ESC key is pressed, the current dialog will be closed, note! Here is said dialog, that is inherited from WX. The Window object for dialog, for WX. Frame using SetID seems to have no effect.

2. Using Timers Timer
In chapter 18 of the Wxpythoninaction, there is an example, as follows:

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 (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 using multi-threading: WX. Callafter

In particular, when writing multithreaded cases in Wxpython, it is important to note that WX is required when a thread notifies a Window object to update state. Callafter. The same is the case for 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. Need to start another GUI program in the program without losing the focus of the main window?
Normally, it is no problem to call Os.popen to run other external programs. However, in Wxpython, WX loses the current focus, even if the program is opened as a modal dialog box. To solve this problem you can use WX's own method, WX. Execute.

The code is as follows:


Wx. Execute (' Notepad ')

V. Learning Resources

1. Official: Http://wiki.wxpython.org/FrontPage

2. Woodpecker Wiki:http://wiki.woodpecker.org.cn/moin/wxpythoninaction

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

  • 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.