Python basic tutorial (Chapter 1 graphical user interface) and python basic tutorial
This article is all from the second version of "Python basics tutorial". Here, I will share my learning path.
______ Welcome reprinted: http://www.cnblogs.com/Marlowes/p/5520948.html ______
Created on Marlowes
This chapter describes how to create a graphical user interface (GUI) for a Python program, that is, windows with buttons and text boxes. Cool, right?
Currently there are many "GUI Toolkit" that support Python, but none of them are considered to be your GUI Toolkit. This is also a good situation (a lot of free space for choice) (others cannot use the program unless they have installed the same GUI toolkit ), fortunately, there is no conflict between the Python GUI toolkit and you can install as many as you want.
This chapter briefly introduces wxPython, the most mature cross-platform Python GUI toolkit. For more information about wxPython, see the official documentation (http://wxpython.org ). For more information about GUI program design, see Chapter 28th.
12.1 rich platforms
Before writing a Python GUI program, you need to decide which GUI platform to use. To put it simply, a platform is a specific set of graphical components that can be accessed by a given Python module called the GUI toolkit. There are many available Python toolkit. Some of the most popular ones are shown in Table 12-1. For a more detailed list, you can search by keyword "GUI" on Vaults of Parnassus (http://py.vaults.ca. You can also find a full list of tools on the Python Wiki (http://wiki.python.org/moin/GuiProgramming. Guiherme Polo has also written a paper on comparison between the four main platforms ("PyGTK, PyQt, Tkinter and wxPython comparison" (comparison of PyGTK, PyQt, Tkinter and wxPython ), the Python Papers, Volume 3, issue 1, 26 ~ Page 37. This article can be obtained from http://pythonpapers.org ).
Table 12-1 Popular Python GUI toolkit
Tkinter uses the Tk platform, which is easy to get and semi-standard. Http://wiki.python.org/moin/TkInter
Wxpython is based on wxWindows and is becoming increasingly popular across platforms. Http://wxpython.org
PythonWin can only be used on Windows, using the Windows GUI feature http://starship.python.net/crew/mhammond of the Local Machine
Java Swing can only be used for Jython and uses the local Java GUI. Http://java.sun.com/docs/books/tutorial/uiswing
PyGTK is popular in Linux because it uses the GTK platform. Http://pygtk.org
PyQt uses the Qt platform and is cross-platform. Http://wiki.python.org/moin/PyQt
There are too many optional packages. Which one should I use? Although each toolkit has advantages and disadvantages, it depends largely on your preferences. Tkinter is actually similar to the standard because it is used in most "formal" Python GUI programs and is part of the Windows binary release. However, you must compile and install it on UNIX. Tkinter and Swing Jython will be introduced in section 12.4.
Another increasingly popular tool is wxPython. This is a mature and feature-rich package, and is also the father of Python Guido van rosum's favorite. In this chapter, we will use wxPython.
For more information about Pythonwin, PyGTK, and PyQt, see the home pages of these projects (see table 12-1 ).
12.2 download and install wxPython
To download wxPython, visit its download page at http://wxpython.org/download.php. This webpage provides detailed instructions on which version to download, as well as the prerequisites for using different versions.
If you are using a Windows system, you should download the pre-built binary version. You can select a version that supports Unicode or does not support Unicode. Unless Unicode is used, the version you choose is not very different. Make sure that the selected binary version corresponds to the Python version. For example, wxPython compiled for Python2.3 cannot be used for Python2.4.
For Mac OS X, you should also select the corresponding Python version of wxPython. You may also need to consider the operating system version. Similarly, you can select a version that supports Unicode and does not support Unicode. The download link and Related explanations can clearly tell you which version to download.
If you are using Linux, you can check whether wxPython is included in the package manager. It exists in many mainstream releases. Different Versions of Linux have different RPM packages. If you are running a Linux release that contains RPM, you should at least download the wxPython and runtime package without the devel package. Once again, you must select the version corresponding to the Python and Linux releases.
If no version is suitable for the hardware or operating system (or Python version), you can download the source code release version. For compilation, you may need to download other source code packages based on various prerequisites, which is beyond the scope of this chapter. These contents are explained in detail on the wxPython download page.
After wxPython is downloaded, it is strongly recommended to download the demo version (demo, which must be installed independently), which contains documents, sample programs, and very detailed (and useful) demo distribution. This demo demonstrates the features of most wxPython and allows you to view the source code in a user-friendly manner-it is worth noting if you want to learn wxPython by yourself.
The installation process should be simple and automatic. Install the Windows 2-in-progress installation only to run the downloaded Executable File (.exe file); In OS X, the downloaded file should look like a CD-ROM that can be opened, with a double-click. pkg file. To use RPM for installation, see the RPM documentation. Both Windows and Mac OS X run an installation wizard, which is easy to use. You just need to select the default settings, keep thinking about Continue, and click Finish.
12.3 create a sample GUI application
To use wxPython for demonstration, first let's take a look at how to create a simple sample GUI application. Your task is to compile a basic program that can edit text files. Writing a full-featured text editor is beyond the scope of this chapter-focus on the basics. After all, the goal is to demonstrate the basic principles of GUI programming in Python.
The function requirements for this small text editor are as follows:
It should allow opening of text files with given file names;
It should allow editing of text files;
It should allow saving text files;
It should allow exit of the program.
When writing a GUI program, it is always a bit useful to draw a sketch of the interface. Figure 12-1 shows a layout that meets our text editing requirements:
Figure 12-1 Text Editor sketch
The interface elements can be used as follows.
Enter the file name in the text box on the left of the button and click Open to Open the file. The text contained in the file is displayed in the text box below.
You can edit the text in this large text box as you like.
If you want to Save the changes, click the Save button to use the text box containing the file name again-and then write the content of the text box into the file.
There is no Quit button-if the user closes the window, the program exits.
It is quite difficult to write such a program in some languages. However, using Python and the appropriate GUI toolkit is a piece of cake (although readers may not agree with this statement now, they should agree after learning this chapter ).
12.3.1 start
To check whether wxPython works, you can try to run the wxPython demo version (to be installed separately ). In Windows, you can find the wxPython Demo file in the Start Menu, while in OS X, you can drag the wxPython Demo file to the application and run it. After reading the demo, you can start to write your own program. Of course, this will be more interesting.
To import the wx module:
import wx
There are many ways to write wxPython programs, but the inevitable thing is to create application objects. The basic application class is called ex. App, which is responsible for all the initialization behind the scenes. The simplest wxPython program should be like the following:
import wxapp = wx.App()app.MainLoop()
NOTE: If wx. App cannot work, you may need to replace it with wx. PySimpleApp.
Because there is no window for user interaction, the program will immediately exit.
In this example, we can see that the methods in the wx package start with an uppercase letter, which is the opposite of the Python habit. The reason for this is that these method names correspond to the method names in the wxWidgets of the basic C ++ package. Although there are no formal rules against the method or function names that start with an uppercase letter, the standard practice is to keep such names for the class.
12.3.2 windows and components
Windows also becomesFramework(Frame), which is only an instance of the wx. Frame class. Components in the wx framework are composedParent partCreated as the first parameter of the constructor. If you are creating a separate window, you do not need to consider the parent part. use None, as shown in code list 12-1. Besides, you need to call the Show method of the window before calling app. MainLoop -- otherwise it will remain hidden (you can call win. Show in the case processing program, which will be introduced later ).
# Code list 12-1 Create and display a framework import wxapp = wx. App () win = wx. Frame (None) win. Show () app. MainLoop ()
If you run this program, a window appears, similar to Figure 12-2.
Figure 12-2 there is only one window GUI Program
Adding a Button to the framework is also easy-you only need to instantiate wx. Button using win as the parameter, as shown in the code list 12-2.
# Code list 12-2 Add the button import wxapp = wx on the framework. app () win = wx. frame (None) btn = wx. button (win) win. show () app. mainLoop ()
In this case, a window with a button is displayed, as shown in figure 12-3.
Figure 12-3 program after adding a button
Of course, this is not enough, the window has no title, the button has no labels, and you do not want the button to overwrite the entire window.
12.3.3 tags, titles, and locations
You can use the constructor's label parameter to set the labels of components when creating them. You can also use the title parameter to set the framework title. I found that the most practical method is to use keyword parameters for the wx constructor, so I don't have to remember the order of parameters. The code list 12-3 demonstrates an example.
# Code list 12-3 add tags and titles Using Keyword parameters import wxapp = wx. App ()
Win = wx. frame (None, title = "Simple Editor") loadButton = wx. button (win, label = "Open") saveButton = wx. button (win, label = "Save ")
Win. Show () app. MainLoop ()
The running result of the program is 12-4.
This version of the program is still somewhat incorrect-it seems that a button is missing! In fact, it's not lost-it's just hidden. Note that the button layout can display hidden buttons. A basic (but not practical) method is to use the pos and size parameters to set the position and size in the constructor, as shown in the code list 12-4.
12-4 window with layout problems
# Code list 12-4 set the button position import wxapp = wx. app () win = wx. frame (None, title = "Simple Editor", size = (410,335) win. show () loadButton = wx. button (win, label = "Open", pos = (225, 5), size = (80, 25) saveButton = wx. button (win, label = "Save", pos = (315, 5), size = (80, 25) filename = wx. textCtrl (win, pos = (5, 5), size = (210, 25) contents = wx. textCtrl (win, pos = (5, 35), size = (390,260), style = wx. TE_MULTILINE | wx. HSCROLL) app. mainLoop ()
As you can see, positions and dimensions both include a pair of values: positions include x and y coordinates, while dimensions include width and height.
There are some new things in this Code: I created twoText Control(Text control, wx. TextCtrl object), each of which uses a custom style. The default text control isText Box(Text field), is a line of editable text, there is no scroll bar, in order to createRegion(Text area) you only need to adjust the style using the style parameter. The value of the style parameter is actually an integer, but you do not need to specify it directly. You can use the bitwise OR operator OR (OR pipeline operator) to combine the style with a special name in the wx module. In this example, I combined wx. TE_MULTILINE to obtain the multi-row scroll area (vertical scroll bar by default) and wx. HSCROLL to obtain the horizontal scroll bar. The running result is 12-5.
Figure 12-5 appropriate components
12.3.4 more intelligent layout
Although it is easy to understand the geometric location of each component, the process is boring. Drawing on the drawing may help to determine the coordinates, but there are many serious disadvantages of using numbers to adjust the positions. If you run the program and try to resize the window, you will notice that the component's geometric position remains unchanged. Although it's not a big deal, it seems a bit strange. When the window size is adjusted, the size and position of the components in the window should be adjusted accordingly.
Consider how I made the layout, so this situation will not be surprising. The position and size of each component are explicitly set, but the behavior of each component is not clear when the window size changes. There are many methods to specify actions. The simplest way to layout in wx is to useSizer(Sizer), the easiest tool to use is wx. BoxSizer.
The sizer manages the size of the component. You just need to add the part to the sizer, add some layout parameters, and then let the sizer manage the size of the parent component on its own. In the preceding example, the background component (wx. panel) to create some nested wx. boxSizer, and then set its sizer using the SetSizer method of the Panel, as shown in code list 12-5.
import wxapp = wx.App()win = wx.Frame(None, title="Simple Editor", size=(410, 335))bkg = wx.Panel(win)loadButton = wx.Button(bkg, label="open")saveButton = wx.Button(bkg, label="Save")filename = wx.TextCtrl(bkg)contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL)hbox = wx.BoxSizer()hbox.Add(filename, proportion=1, flag=wx.EXPAND)hbox.Add(loadButton, proportion=0, flag=wx.LEFT, border=5)hbox.Add(saveButton, proportion=0, flag=wx.LEFT, border=5)vbox = wx.BoxSizer(wx.VERTICAL)vbox.Add(hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)vbox.Add(contents, proportion=1, flag=wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, border=5)bkg.SetSizer(vbox)win.Show()app.MainLoop()
The running result of this Code is the same as that of the sequence, but relative coordinates instead of absolute coordinates are used.
The wx. BoxSizer constructor has a parameter (wx. HORIZONTAL or wx. VERTICAL) that determines whether the constructor is HORIZONTAL or VERTICAL. The default value is HORIZONTAL. The Add method has several parameters. The proportion parameter changes the size of the allocated space in the hour according to the window. For example, in the horizontal BoxSizer (the first one), the filename component obtains all the extra space when it is changed. If all three parts set proportion to 1, the space will be equal. You can set proportion to any number.
The flag parameter is similar to the style parameter in the constructor. You can use a bitwise OR operator to connect a constructor (symbolic constant) to construct a constructor. The wx. EXPAND flag ensures that the component is extended to the allocated space. However, the wx. LEFT, wx. RIGHT, wx. TOP, wx. BOTTOM, and wx. ALL labels determine the edge to which the border parameter is applied. The border parameter is used to set the edge width (interval ).
That's it. I get the layout I want. However, a very important thing is missing-nothing happens when you press the button.
Note: For more information about the sizer or wxPython, see the wxPython demo version, which contains the content and sample code you want to know. If it looks hard, you can access wxPython's website http://wxpython.org.
12.3.5 event handling
In GUI terms, a user-executed action (such as clicking a button) is calledEvent(Event ). You need to let the program pay attention to these events and respond. You can bind a function to a component that may occur at the time involved to achieve this effect. When an event occurs, the function is called. The Bind method of the component can be used to link the time processing function to a given event.
Assume that a function is written to open a file and named it load. Then you can use this function as the loadButton event handler as follows:
loadButton.Bind(wx.EVT_BUTTON, load)
Intuitive, isn't it? I linked the function to the button. When I clicked the button, the function was called. A symbolic constant named wx. EVT_BUTTON representsButton event. The wx framework has such event constants for various events-from mouse actions to keyboard buttons, and so on.
Why use LOAD?
Note: It is not accidental that I use loadButton and load as the button and handler name, even though the text of the button is "Open ". This is because if I call the button openButton, open will naturally become the name of the event processing function, which conflicts with the file opening function open created in the internal system, resulting in the latter being invalid. Although there are many ways to solve this problem, I think using different names is the easiest.
12.3.6 completed procedures
Let's do the rest. Now we need two event processing functions: load and save. When an event processing function is called, it will receive an event object as its unique parameter, including information about what happened, but this can be ignored here, because the program only cares about what happens when you click it.
def load(event): file = open(filename.GetValue()) contents.SetValue(file.read()) file.close()
After reading chapter 1, you should be familiar with the open/read part of the file. The file name is obtained using the GetValue method of the filename object (filename is a small text box ). Similarly, to introduce text into the attention area, you only need to use contents. SetValue.
The save function is also very simple: it is almost the same as load-except that it has a "w" mark and the write Method Used for file processing. GetValue is used to obtain information from the partition.
def save(event): file = open(filename.GetValue(), "w") file.write(contents.GetValue()) file.close()
That's it. Now I bind these functions to the corresponding buttons and the program can run. The final program is shown in the code list 12-6.
#! /Usr/bin/env python # coding = utf-8import wxdef load (event): file = open (filename. getValue () contents. setValue (file. read () file. close () def save (event): file = open (filename. getValue (), "w") file. write (contents. getValue () file. close () app = wx. app () win = wx. frame (None, title = "Simple Editor", size = (410,335) bkg = wx. panel (win) loadButton = wx. button (bkg, label = "open") loadButton. bind (wx. EVT_BUTTON, load) saveButton = wx. button (bkg, label = "Save") saveButton. bind (wx. EVT_BUTTON, save) filename = wx. textCtrl (bkg) contents = wx. textCtrl (bkg, style = wx. TE_MULTILINE | wx. HSCROLL) hbox = wx. boxSizer () hbox. add (filename, proportion = 1, flag = wx. EXPAND) hbox. add (loadButton, proportion = 0, flag = wx. LEFT, border = 5) hbox. add (saveButton, proportion = 0, flag = wx. LEFT, border = 5) vbox = wx. boxSizer (wx. VERTICAL) vbox. add (hbox, proportion = 0, flag = wx. EXPAND | wx. ALL, border = 5) vbox. add (contents, proportion = 1, flag = wx. EXPAND | wx. LEFT | wx. BOTTOM | wx. RIGHT, border = 5) bkg. setSizer (vbox) win. show () app. mainLoop ()GUI. py
Follow the steps below to use this editor.
(1) run the program. We should see a window similar to the one just now.
(2) Make some words in the hosts area (for example, "Hello, world! ")
(3) In the example box, click the file name (for example, hello.txt ). Make sure the file does not exist. Otherwise, it will be overwritten.
(4) Click Save.
(5) Close the editing window (for fun only ).
(6) restart the program.
(7) type the same file name in the text box.
(8) Click Open. The text content of the file should be reproduced in the large text area.
(9) edit the file and save it again.
Now you can open, edit, and save the file until you are bored-and you should consider improving it. For example, how does the urllib module allow the program to download files?
Readers may consider using a more object-oriented design in their programs. For example, you may want to manage the primary application as an instance of a custom application class (possibly a subclass of wx. App), rather than placing the entire structure at the top of the program. You can also create a separate window class (subclass of wx. Frame ). See Chapter 28th For more examples.
How about PYW?
In Windows, you can use. pyw as the end of the file name to save the GUI program. In chapter 1, I told you to use the end Of the file name and double-click it (in Windows). Nothing happened. Then I promise I will explain it later. In Chapter 10, I once again mentioned this, and I will explain it in this chapter, so let's talk about it now.
Actually, it's no big deal. When double-clicking a common Python script in Windows, a DOS window with a Python prompt will appear. If print and raw_input are used as the basic interface, there will be no problem. But now that you know how to create a GUI program, the DOS window is redundant, the truth behind the pyw window is that it can run Python without a DOS window-perfect for GUI programs.
12.4, but I would rather use it ······
There are too many Python GUI toolkits, so I cannot show you all of them. However, I can give examples in some popular GUI packages (such as Tkinter and Jython/Swing ).
To demonstrate different packages, I created a simple program, which is simpler than the previous editor example. There is only one window that contains a button with the "Hello" label. When you click the button, it prints the text "Hello, world! ", For simplicity, I have not used any special Layout features. The following is an example of the wxPython version.
import wxdef hello(event): print "Hello, world!"app = wx.App()win = wx.Frame(None, title="Hello, wxPython!", size=(200, 100))button = wx.Button(win, label="Hello")button.Bind(wx.EVT_BUTTON, hello)win.Show()app.MainLoop()
The final result is 12-6.
Figure 12-6 simple GUI example
12.4.1 use Tkinter
Tkinter is an old Python GUI program. It is packaged by the Tk GUI toolkit (for the Tcl programming language. By default, Windows and Mac OS versions are included. The following url may be useful:
Http://www.ibm.com/developerworks/linux/library/l-tkprg
Http://www.nmt.edu/tcc/help/lang/python/tkinter.pdf
The following is a GUI program implemented using Tkinter.
From Tkinter import * def hello (): print "Hello, world! "Win = Tk () # Tkinter's main window win. title (" Hello, Tkinter! ") Win. geometry ("200x100") # Size 200,100 btn = Button (win, text = "Hello", command = hello) btn. pack (expand = YES, fill = BOTH) mainloop ()
12.4.2 using Jython and Swing
If you are using Jython (Java Implementation of Python), packages such as wxPython and Tkinter cannot be used. The only available GUI toolkit is the Java standard library package AWT and Swing (Swing is the latest and considered a standard Java GUI toolkit ). The good news is that both of them are directly available and do not need to be installed separately. For more information, visit the Java website and the Swing document for Java:
Http://www.jython.org
Http://java.sun.com/docs/books/tutorial/uiswing
The following is a GUI example implemented using Jython and Swing.
from javax.swing import *import sysdef hello(event): print "Hello, world!"btn = JButton("Hello")btn.actionPerformed = hellowin = JFrame("Hello, Swing!")win.contentPane.add(btn)def closeHandler(event): sys.exit()win.windowClosing = closeHandlerbtn.size = win.size = 200, 100win.show()
Note that an additional event handler (closeHandler) is added here, because the close button does not have any useful default behavior in Java Swing. In addition, you do not need to explicitly enter the main event loop because it runs in parallel with the Program (in different threads ).
12.4.3 use other Development Kits
Most GUI toolkit have the same basics, but unfortunately, when learning how to use a new package, it takes a lot of time to find a way to learn new packages by making everything you want to do. So before deciding which package to use (where to start some help in section 12.1), you should take some time to think about it, and then write code in the document. I hope this chapter provides the basic concepts required to understand the document.
Conclusion 12.5
Let's review what we have discussed in this chapter.
Graphical user interface (GUI): GUI Can make programs more friendly. Although not all programs require them, the GUI may be helpful when the program needs to interact with the user.
Python GUI platform: Python programmers have many GUI platforms available. Although there are so many choices, it is sometimes difficult to choose.
WxPython: wxPython is a mature and distinctive cross-platform Python GUI toolkit.
Layout: You can directly place the component at the desired position by specifying the geometric coordinates. However, you need to use the layout manager to change the size of the window containing them. The layout mechanism in wxPython isSizer.
Event Processing:Event. In any application, the program will respond to these events, otherwise the user will not be able to interact with the program. The event handler function in wxPython is added to the component using the Bind method.
What to learn next
This is the content of this chapter. I have learned how to write programs that interact with the external world through files and guis. The next chapter describes the important component of many other program systems: database.