WxPython Introductory Tutorials _python

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

This article is about WxPython, but WxPython is actually a combination of two things: the Python scripting language and the Wxwindows Library of GUI functionality (for an introduction to wxwindows, see "Detail on Developerworks" on Wxw Indows " ). The Wxwindows library is for the maximum portability of C/s + + libraries, while extracting GUI functions. So wxwindows applications are inherently capable of running on Windows, with X, KDE or Gnome UNIX or wxwindows ported platforms (unfortunately, not including the Macintosh). Of course Python, as a scripting engine, has a strong portability (it 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 WxPython applications are fast and easy to write, and can run in Windows or UNIX environments without making any changes.

You might think, "but that's why I have Java, and Java is also 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 want it to, and worst of all, with all due respect, the Java window is not really a window, so the interaction between the Java Virtual machine and the host system is always a bit inadequate.

Python, on the other hand, occupies a relatively small space. The WxPython Library window is a really real local window that can do anything the local window can do, making 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 find that doing the same thing, WxPython is much easier than Java.

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

The world's smallest WxPython program, anatomy!

Sounds cool, doesn't it? Let's look at some code and you'll understand what I'm saying. For ease of discussion, I inserted some row labels in the example. They are not part of the code; This is why they are expressed in blue Italic .


Listing 1. A 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 ()


It's easy to see how the code works if we look at it in a row. That's why it's the smallest WxPython program in the world (I've eliminated all extraneous 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's under Windows (I've entered something in it):






Let's look at the code

The first and second lines are important and need them later. In fact, in this case, there's no need to sys and os , but since almost every program needs to be used, put them in this code and ask them some questions later. The second row 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 There are no semicolons at the end of these lines. If you've written a Perl program, it takes a little effort to familiarize yourself with Python's input habits. But wait, it's strange to you.

In the third line, we define the first Python class-- main_window . main_windowA class is a derived class of a class that is defined in the WX module wxFrame . As you can guess, any window is a wxFrame class.

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

Up to now, if you have written C + +, you must be wondering why there are no 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 the indentation under that line belongs to the statement terminated by the colon. This piece is finished when the indent reverts to the original indentation. Even more strangely, this arrangement is actually very useful, and programmers who have just begun to program find it easier than using curly braces to illustrate the structure. Fortunately, this also means fewer keystrokes, so older programmers can accept it.

So lines 5th, 6, and 7 of indentation belong to the method defined in line 4th. They call the initialization routines of the Wxframe parent class (all the heavy work that actually sets 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 have written any Microsoft Windows code, you will soon like WxPython by resizing the control to match the parent window. The practical meaning of line 6th is to complete a Notepad-like editor. That's not much. With C + + code, you need more to achieve it, don't you? 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. Line 8th defines the wxApp objects that are derived from the class App . It specifies the application object, and when run, creates an main_window object and sets it to the top window.

Finally define the class, create the Application object, and start running its main loop. If you have done any of the C + + Windows programming, you will realize that the Mainloop method is a normal event loop for all Windows programs. The style of the startup code is indeed consistent with the scripting language. Remember, the Python interpreter reads the code line by row and executes it while reading. So once the 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 that can be run on Windows or UNIX without modification. And it's easy to add more features, that's great, that's what you'll be talking about in the next section.


What about the performance?

You might think, "interpreted language, is inefficient." For larger programs, it can be slow to execute. "To a certain extent, this is correct." In fact, any code that affects performance is usually implemented in C/s + + and linked to the Python interpreter, which is easy to do. So Python is often used as a binder for binding functional modules and GUI display (or application server functionality if you need this feature). But as a binder, Python is very effective. You can use Python to implement real programs in a very short period of time, usually for several weeks due to their limited object-oriented and format creation opportunities.

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

What you lose here is in terms of performance (actually, very little), but you can easily make up for it by simplifying the implementation and (more importantly) simplifying customization. In fact, by including Python, you've automatically included a scripting language that's easy to show to your users, and for beginners of programming, the language proves it's easy to learn. 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!


The more interesting thing: the initial project builder

Anyway, the point here is to show you 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 basic organization. I use an extended version of CVS (standard open source version control system) front-end. here is the code . Our (still fairly small) application extends from 15 lines to about 300 lines, but it does a lot of things now.




Interesting things in the program

I don't have the line number listed in Listing 2 because it's obvious that you'll have to read the code months anyway. I'm just going to tell you a general story about what this program does and what Python and WxPython functions it uses. For more details on Python, ask your local bookstore for the book O ' Reilly written by Mark Lutz, or read the documentation with Python (Guido Rossum, the actual author of Python).

The first interesting thing is that the application handles the command line. The list sys.argv is the command line, and in order to use it you need to understand the Python list syntax. The syntax for this example is very basic, but that'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 self a parameter that contains a reference to the object being invoked. (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__ way. Instead of building a simple menu of controls like the previous example, we build a menu bar, attach menu events to callback routines, and build window splits, tree controls, and edit controls. You can skim these to see how the whole job is. (If you have not done GUI programming before, you will find it difficult to look down.) Visual Basic can do all of this in a behind-the-scenes way, but you can still see it if you just open the form file in a text editor. If you have done GUI work with C + +, it will feel very familiar.

Once we have the constructed window, we can then look at the actual code of the program. First, __init__ there are two methods that are used to load and save the project file after the method. There you can see how Python open handles file I/O with, and so on. Note that, in fact, closing a file is a breeze-as it happens, for Python, the file handle is just a memory-managed object, and the object is referenced by the counter. When the reference becomes invalid, Python knows it and clears it, and the file closes automatically. There is also a situation that cannot be fully trusted (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 collecting useless information (non-C people like to discuss the problem).

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

The remaining problem with the new code is the event handler, which is used to handle the process encountered during the execution of the program. I again let the program explain most of itself. Note that you use General dialog boxes ( wxMessageDialog , wxFileDialog and wxTextEntryDialog ) to handle many of the regular user interactions. These calls are a little different from the corresponding usage of general Windows programming, here I give you some clues: first, the dialog box is an object created by a reasonable call, which is ShowModal() displayed, used, and destroys it; second, the user clicks the button to return from the return value ShowModal() , You can get additional values by using a dialog-attached method. For example, during file dialog interaction, the path that the user chooses is dlg.GetPath() obtained as a. This is quite different from how the Windows API works. 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 that situation. Things will get better in the second half. At the same time, Python itself has some good books, where 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, there are some specific Python annotations, but in many cases you will find that you have to read the demo code along with WxPython, or you must ask the expert in your mailing list for your question. Fortunately, these experts are "traceable".

Once you have passed the initial learning curve, you will find this much simpler than doing the same task in the Windows API. Believe me, this material is very good.



Resources

  • For an introduction to Wxwindows, see "detailed Wxwindows"on Developerworks.
  • The WxPython home page links to this document, downloads, and related sites. The site is mirrored in SourceForge , it has been linked to Wxwindows, WxPython mailing lists, and so on. You can also download Wypython here.
  • Find downloads, latest developments, and documentation on the Python language Web site for the Python language.
  • Programming python Mark Lutz (O ' Reilly, 1996), ISBN 1-56592-197-6, is a reference book I use in Python. It's not so much a reference book as a tutorial, it's the best book I've found so far.
  • If you want to use your head, you can read Christian Tismer's stackless Python, which effectively implements collaborative routines, generators, continuations, and micro-threading. If you can't afford this kind of mental exercise, please don't try it easily.
  • Vaults of Parnassu's Python resource is the best regular beginner's corner for information on the Text-based user interface tools in Python.
  • Python.net is a development garden for. NET Python.
  • The Ninth International Python Conferencewas held in March.
  • Read excerpts from the book jpython:the felicitous Union of Python and Java, Learning python (O ' Reilly, 1999).



About the author

Michael Roberts has been in programming for 13 years. This article was written by him a few months ago. You can send him E-mail michael@vivtek.com   or visit his website  . 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.