WxPython Getting Started Tutorial

Source: Internet
Author: User
Tags version control system python list

This article is about WxPython, but WxPython is actually a combination of two things: the Python scripting language and the GUI functionality of the Wxwindows library (for an introduction to Wxwindows, see the Developerworks WS "). The Wxwindows library is designed to extract GUI functionality for the most portable, C + + libraries. So the Wxwindows app is inherently capable of running on Windows, UNIX with X, KDE or Gnome, or wxwindows ported to a platform (unfortunately, not including the Macintosh). Of course, Python, as a scripting engine, has a strong portability (which can run on the Macintosh, but it doesn't work if you want to write desktop GUI code). Combining Wxwindows with the Python scripting language means that the WxPython application is fast and easy to write, and can run in a Windows or UNIX environment without any changes.

You might think, "but that's why I have Java, and Java is portable." "Yes, if you've ever tried to install Java applications on Windows, you might realize that's not the case at all." The Java Virtual machine is big, it doesn't always work the way you think, and worst of all, with all due respect, Java windows are not really windows, so the interaction between the Java Virtual machine and the host system is always a bit out of the box.

Python, on the other hand, occupies a relatively small space. WxPython Library window is a real local window, it can do anything local window can do, make your WxPython program like a window program. All of WxPython's possessions can be packaged into an easy-to-install package. Maybe I am a stubborn person, but I found that doing the same thing, WxPython is much easier than Java.

But you may not have heard of Python on the desktop, it is a member of the server-side programming community, a newborn child of the scripting language (especially with the application Server framework, such as Zope). Now people are catching up with the Python craze. The advantage of Python is that, unlike other scripting languages, it starts out as an object-oriented language. So you won't lose sight of Java's taste for OO benefits because of its love for Python.

The world's smallest WxPython program, anatomy!

Sounds cool, doesn't it? Let's look at some code and you'll see what I'm talking about. For ease of discussion, I inserted some row labels in the example. They are not part of the code, which is why they are represented in blue italics .


Listing 1. A very small sample of code



[1]

Import sys, OS


[2]

From WXPYTHON.WX Import *


[3]

Class Main_window (Wxframe):


[4]

def __init__ (self, parent, ID, title):


[5]

Wxframe.__init__ (self, parent,-1, title, size = (200, 100),

Style=wxdefault_frame_style|wxno_full_repaint_on_resize)


[6]

Self.control = Wxtextctrl (self,-1, Style=wxte_multiline)


[7]

Self. Show (True)


[8]

Class App (Wxapp):
def OnInit (self):
frame =
Main_window (None,-1, "WxPython: (A demonstration)")

Self. Settopwindow (frame)
return True


[9]

App = App (0)
App. Mainloop ()


We look in line, so it's easy to see how the code works. That's why it's the smallest WxPython program in the World (I've removed all irrelevant details). This code can only create a window with an edit field in the area. You can edit it in this field, but obviously there is no way to save it. The application looks like it was under Windows (I entered something in it):






Let's look at the code

The first and second lines are important and will need them later. In fact, in this example, it is not necessary sys and os , but because almost every program needs to be used, so first put them into this code, in the following will be a few questions for them. The second line is more interesting and imports the WxPython WX library. Of course, the WX Library (basic WxPython Declaration) includes basic classes, such as frameworks and applications.

/Note that there is no semicolon at the end of these lines. If you've written a Perl program, it takes a little bit of familiarity with Python's input habits. But wait, it's strange for you.

In the third line, the first Python class is defined-- main_window . main_windowclass is a derived class of a class that is defined in the WX module wxFrame . As you suspect, any window is a wxFrame class.

In line fourth, the initialization method is defined, the main_window only method that needs to be defined (and, of course, the other in the Wxframe Class). The initialization method takes arguments parent , and id , of course, title also (as a reference to the object) self . selfparameter is the first parameter of all Python methods.

Up to now, if you've written C + +, you'll be wondering why you don't have curly braces. It's strange that Python treats indentation as an important syntax. Any statement with a child statement ends with a colon, and all indentation under that line belongs to the statement terminated with that colon. This piece is finished when the indentation is returned to the original indentation. Even more strangely, this arrangement is actually very useful, as programmers at the beginning of programming find it easier to illustrate the structure with curly braces. Fortunately, it also means fewer keystrokes, so older programmers can accept it.

So the indents of lines 5th, 6, and 7 belong to the method defined in line 4th. They call the initialization routines of the Wxframe parent class (which actually sets all the heavy lifting of a window), define a control to fit the new main window, and make sure that the window is visible.

WxPython will resize the parent window unless specifically told not to do so. If you've ever written any Microsoft Windows code to match the parent window by resizing the control, you'll soon like WxPython. The practical meaning of line 6th is to complete an editor like Notepad. It's not much of a thing. You need more to be able to do this with C/+ + code, right? Remember--what we're doing here is not a fixed-size dialog, it's a windows-application that's really in the window body and resizable with an editor.

Let's move on. The 8th line defines the wxApp object that is derived from the class App . It specifies the application object when it is run, creates an main_window object, and sets it as the top window.

Finally, define the class, create the Application object, and start running its main loop. If you have done any programming with C + + windows, you will recognize that the Mainloop method is a normal event loop for all Windows programs. The style of the boot code is really consistent with the scripting language. Remember, the Python interpreter reads the code lines by line and executes it while reading. So, once a class is defined, we just call it in the script.

That's it. In these 15 lines of code, a simple text editor is implemented, which can be run on Windows or UNIX without modification. And it's easy to add more features, which is great, and will be covered in the next section.


How's the performance?

You might think that "interpreted language is inefficient." For larger programs, execution can be slow. "To a certain extent, this is correct. In fact, any code that affects performance is often re-implemented in C/s + + and linked to the Python interpreter, which is easy to do. So Python is typically used as a binder for binding functional modules and GUI displays (or application server functionality if you need that functionality). But as a binder, Python is very effective. You can implement real programs in Python in a very short time, and they can typically be used for several weeks due to their limited opportunity to create objects and formats.

Also, if you suspect the idea of combining large programs with an interpreted language, you might want to consider how the earlier versions of Microsoft Word were implemented. At least the most recent word version of Windows 6.0, its word Basic function is actually just compiled code, and the GUI is built by the Pcode interpretive language. (MS Word 6.0 is written in Word Basic and works well, which is a clever design, one of the reasons-it's the first desktop program to use the built-in interpreter.) )

What you lose here is in terms of performance (actually, rarely), but you can easily compensate by simplifying the implementation and (more importantly) simplifying the customization. In fact, by including Python, you have automatically included a scripting language that is easy to present to your users, and the language proves easy to learn for novice programmers. If you delve into it, you can create world-class software with less effort than you now spend. Because, if the language can serve Microsoft, it can also serve you!


Something more interesting: preliminary project builder

Anyway, to get to the point, here's a program that actually does something worth doing. This program lets you create a list of text files called projects. You can edit and save them. More importantly, you can easily see how to further enhance the base builder. I use an extended version of the CVS (standard open source version control system) front end. Here is the code. Our (still quite small) application extends from 15 lines to about 300 rows, but it can now do a lot of things.




Interesting things in the program

The line number is not listed in Listing 2 because it is obvious that you will be reading the code in the month anyway. I'm just going to talk a little bit about what this program does and what the Python and WxPython functions are. For more details about Python, ask your local bookstore to find the O ' Reilly book written by Mark Lutz, or read the documentation along with Python (Guido Rossum, the actual author of Python).

The first interesting thing is that this application handles the command line. The list sys.argv is the command line and you need to understand the Python list syntax in order to use it. The syntax for this example is basic, but it's enough to make you understand the program.

Next, in order to be easy to use when debugging, define a MsgBox function. Note that the syntax for function declarations and class method declarations is exactly the same. The only difference is that the class method requires a parameter self that contains a reference to the object being called. (Of course, you don't necessarily call it "self.") But if you don't, you'll be confused. )

What's really interesting is in the more complex __init__ approach. Here, instead of building a simple, lack-of-control menu like the previous example, we built a menu bar, attached menu events to callback routines, and built window splitter bars, tree controls, and edit controls. You can skim over these to see how the whole job works. (If you haven't done GUI programming before, you'll find it hard to look down.) Visual Basic can do all of this in a way behind the scenes, but you can still see it if you just open the table file in a text editor. If you've ever done a GUI job with C/C + +, you'll feel familiar.

Once a constructed window is available, we can then look at the actual code of the program. First, __init__ there are two ways to load and save a project file after the method. There you can see how Python uses open and so on to handle file I/O. Note that, in fact, closing a file is a breeze-as it happens, for Python, the file handle is simply a memory-managed object, and the object is referenced by a counter. When the reference becomes invalid, Python knows and clears it, and the file closes automatically. There is also a situation where you cannot fully trust (the file cannot be closed automatically), for example, you will open the written file again and read it. At this point, you want to explicitly close it. This problem is the problem of useless information collection (not C people like to discuss the problem).

Another interesting feature of loading/saving functions is that they encounter exceptions (exceptions) resulting from bad file calls IOError . I let the code explain myself, but that's how you do it, kids.

The remaining problem with the new code is the event handler, which handles what is encountered during the execution of the program. Again I let the program myself to illustrate most. Note that you use a generic dialog box ( wxMessageDialog , wxFileDialog and wxTextEntryDialog ) to handle many regular user interactions. There is a difference between these calls and the corresponding usage of "general" Windows programming, and here are just a few clues: first, the dialog is an object created by a reasonable invocation, which is ShowModal() displayed, exhausted, and destroyed, and secondly, the button that the user clicked returns from the returned value ShowModal() , Additional values can be obtained by using the method attached to the dialog box. For example, the path selected by the user during the file dialog interaction is dlg.GetPath() obtained as a. This is quite different from how Windows APIs work. That's exactly what you know.


Document Status

Let me say that the documentation for the Wxwindows API is in ... In development. The biggest weakness of this platform is the lack of good documentation, and I am actively changing this situation. The situation will improve in the second half. At the same time, Python itself has some good books, of which Python's online documentation is not bad. The documentation for wxwindows,c++ is good. Sometimes, in the Python framework, how to make these documents reasonable is quite mysterious. There are some specific Python comments, but in many cases you will find that you have to read the demo code along with WxPython, or you must ask the experts in the mailing list for your question. Fortunately, these experts are "traceable".

Once you've passed the initial learning curve, you'll find it much easier than doing the same task in Windows API. Believe me, this material is very good.



Resources

  • For an introduction to Wxwindows, refer to "Wxwindows" on Developerworks.
  • The WxPython home page links to the document, downloads, and related sites. The site is mirrored in SourceForge, which has been linked to wxwindows related people, WxPython mailing lists, and so on. You can also download the Wypython here.
  • Find downloads, latest developments, and documentation on the Python language website on the Python language web site.
  • Programming python Mark Lutz (O ' Reilly, 1996), ISBN 1-56592-197-6, is my reference book using Python. It is not so much a reference book as a tutorial, it is the best book I have found so far.
  • If you want to brainstorm, you can read Christian Tismer's stackless Python, which effectively implements the collaboration routines, generators, continuations, and micro-threading. If you can't afford this kind of mental exercise, don't try it easily.
  • Vaults of Parnassu python resources is the best regular beginner's corner to get information about the text-based user interface tool in Python.
  • Python.net is the development corner for Python for. Net.
  • The ninth International Python Conference, held in March.
  • Read the excerpt from the book Jpython:the felicitous Union of Python and Java, learning python (O ' Reilly, 1999).



About the author

michael Roberts has been engaged in programming for more than 13 years. This article was written by him a few months ago. You can send him an e-mail michael@vivtek.com or visit his website www.vivtek.com. The more the better.

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