A brief introduction to the tutorial using TK for GUI programming under Python _python

Source: Internet
Author: User
Tags naming convention pack wrapper wrappers

I'd like to introduce you to the simplest way to start GUI programming, which is to use the Scriptics TK and tkinter wrappers. We'll make a lot of comparisons with the curses library mentioned in "Curses programming in Python" in DeveloperWorks. In addition to the difference between curses implementing the text console and TK implementing the GUI, the two libraries have surprisingly similar interfaces. Before you can use any library, you need to have a basic understanding of Windows and event loops, and refer to the widgets available. (Good, good reference and right amount of practice.) )

As with articles on curses, this article only discusses the characteristics of the tkinter itself. Since many Python distributions have tkinter, there may be no need to download support libraries or other Python modules. The resources later in this article point to a collection of several higher-level user interface widget widgets, but you can do many things with Tkinter itself, including building your own advanced widget. Learning the basic Tkinter module will introduce you to the TK mindset, which is still important even if you continue to use a more advanced widget collection.
TK Brief Description

TK is the most closely related to Tcl language, and widely used graphics library, Tcl language and TK are developed by John Ousterhout. Although TK appeared as a X11 library in 1991, it was actually ported to every popular GUI since then. (It is similar to the case where Python gradually has a "standard" GUI.) Now, most popular languages and many small languages have TK bindings (Tkinter modules).

Before I begin, I must confess that I am not a small, withered, TK-programming expert. In fact, most of my TK programming experience started about three days before I wrote this article. The three days were not without challenges, but in the end I thought I had a good grasp of tkinter. What I'm going to say here is that the TK and tkinter wrappers are designed to be very good, user-friendly, and just the simplest introduction to GUI programming.

Starting with the test application

We will use txt2html, the wrapper for the file format converter used in many previous columns (see Resources), as a test application. Although txt2html can be run in several ways, the wrappers here are running txt2html from the command line. The application runs as a batch process with command line arguments that indicate the various aspects of the transformation to be performed. (Later, it is a good idea to provide the user with an interactive selection screen option to lead the user to gradually select different conversion options and provide visual feedback for the selected option before performing the actual conversion.) )

Tk_txt2html is based on the top menu with a drop-down menu and a nested submenu. There is a detailed implementation note next to it, which looks like the Curses version discussed in "Curses Programming in Python." While TK can achieve more functionality with less code, it is clear that tk_txt2html and curses_txt2html are very similar. For example, in TK, an attribute such as a menu can be implemented by a built-in Tkinter class without having to write from scratch.

In addition to setting configuration options, the TK wrapper includes a scrolling help box built with the TK Text widget (a "about" box with the message widget) and a History window for TK dynamic geometry management. As with most interactive applications, the wrapper accepts some user input with the Entry widget for TK.

Before we discuss the code further, let's take a look at the applications that are actually running.

Learn basic knowledge

In fact, the Tkinter program only needs to do three things:
The smallest [Tkinter] program

Import Tkinter # import the Tkinter module
root = tkinter.tk () # Create a root window
root.mainloop () # Create an Event loop

This is a fully effective Tkinter program (don't mind that it's not practical, because it doesn't even manage "Hello World"). The only thing that the program needs to do is create some widget that holds its root window. After this enhancement, the program's root. Mainloop () method invocation can handle all user interactions without further interference from the programmer.

Main () function

Now, let's take a look at tk_txt2html.py's more realistic main () function. Note that I prefer to use the import Tkinter statement of John Grayson instead of from Tkinter import (see the books listed in resources). This is not because I am concerned about namespace interference (the usual warning from the import statement), but because I want to explicitly use the Tkinter class; I don't want to risk confusing them with my own functions and classes. It is recommended that you do the same, at least at the beginning.
tk_txt2html Main () function

def main (): Global root, history_frame, info_line root = tkinter.tk () root.title (' txt2html Tk Shell ') init_vars () #- -Create the menu frame, and menus to the menu frame Menu_frame = tkinter.frame (root) menu_frame.pack (fill=tkinter.x, si De=tkinter.top) Menu_frame.tk_menubar (File_menu (), Action_menu (), Help_menu ()) #--Create The history frame (to be fille D in during runtime) History_frame = Tkinter.frame (root) history_frame.pack (fill=tkinter.x, Side=tkinter.bottom, pady=2 ) #--Create the info frame and fill with initial contents info_frame = Tkinter.frame (root) info_frame.pack (fill=tkinte R.x, Side=tkinter.bottom) # I put the column labels in a sub-frame left, Label = Tkinter.left, Tkinter.label # Short Cut names Label_line = Tkinter.frame (Info_frame, relief=tkinter.raised, borderwidth=1) label_line.pack (side= Tkinter.top, padx=2, Pady=1) label (Label_line, text= "Run #", width=5). Pack (side=left) label (Label_line, text= "Source:" , width=20). Pack (Side=left) Label (LabeL_line, text= "Target:", width=20). Pack (side=left) label (Label_line, text= "Type:", width=20). Pack (side=left) label (  Label_line, text= "Proxy Mode:", width=20). Pack (side=left) # then put the ' next run ' information in a sub-frame info_line = Tkinter.frame (info_frame) info_line.pack (Side=tkinter.top, padx=2, Pady=1) update_specs () #--Finally, let ' s actuall

 Y do all this stuff created above Root.mainloop ()

There are a few things to note in this simple main () function:

Each widget has a parent. Whenever you create a widget, the first argument that is passed to the instance is the parent of the new widget.
If there are other widgets that create the arguments, they are passed by name. This feature of Python gives us great flexibility in specifying options or allowing them to take default values.
There are several window widget instances (Frame) that are global variables. You can make them local by passing variables between functions to maintain the theoretical purity of the scope of the code, but it's too cumbersome to compare with its actual usefulness. In addition, making these basic UI elements global underscores the fact that they can be used throughout the function. However, be sure to use a good naming convention for your own global variables. (Give you a warning beforehand that Python people seem to hate Hungarian symbols.) )
After creating the widget, we call a geometry manager to let TK know where to place the widget. TK has a lot of magic in computing details, especially when resizing windows or dynamically adding widgets. In any case, however, TK will need to know which spells to use.

Apply the Geometry Manager

TK provides three geometry managers:. Pack (),. Grid (), and. place (). Although. place () can be used for fine (in other words, very complex) control, Tk_txt2html uses only the first two. Most of the time, you will use. Pack ().

Of course, you can call the. Pack () method without the arguments. But if you do that, the widget may end somewhere in the display screen, and you might want to provide some hints for. Pack (). The most important of these hints is the side argument. The possible values are left, right, top, and BOTTOM (note that these are variables in the Tkinter namespace).

A lot of the magic of. Pack () comes from the fact that you can nest widgets. In particular, the Frame widget has little to do except as a container for other widgets (it sometimes shows different types of boundaries). This makes it easy to arrange several frames in the direction you want, and then add other widgets to each frame. Arrange them according to the order of the. Pack () method of the calling frame (and other widgets). Therefore, if two window widgets request Side=top, the first incoming request is satisfied.

Tk_txt2html also occasionally uses. Grid (). The grid Geometry Manager overwrites the parent window widget with a visual coordinate line. When the widget calls. Grid (Row=3, column=4), it requests its parent to place it on the third row, column fourth. Calculates the total number of rows and columns for the parent by looking at the request of all descendants of the parent generation.

Don't forget to apply the Geometry manager to your widgets so that you don't regret seeing them on the display screen.


Menu

Tkinter can easily generate menus. Although we use very simple examples here, you can populate menus with different fonts, graphics, check boxes, and a variety of chic descendant widget widgets if you prefer. In our example, the Tk_txt2html menu is all created with the rows we see above.

Menu_frame.tk_menubar (File_menu (), Action_menu (), Help_menu ())

The line itself may be somewhat mysterious. Most of the work that must be done is in a function named *_menu (). Let's take a look at the simplest example.
Create a Drop-down menu

Def help_menu ():
 help_btn = Tkinter.menubutton (menu_frame, text= ' help ', underline=0)
 Help_btn.pack (side= Tkinter.left, padx= "2m")
 Help_btn.menu = Tkinter.menu (help_btn)
 Help_btn.menu.add_command (label= "How to", Underline=0, Command=howto)
 Help_btn.menu.add_command (label= "about", Underline=0, command=about)
 help_btn [' menu '] = help_btn.menu return
 help_btn

A Drop-down menu is a Menubutton widget that takes the menu widget widget as a descendant. Pack () (or. Grid (), etc.) arranges the Menubutton in the appropriate place. The Menu widget widget adds an item using the. Add_command () method. (Please note the odd allocation made for the Menubutton directory above.) Don't ask why, follow me and do it in your own code. )


Get user Input

The example below shows how the Label widget widget displays input (complete resources for some examples of the Text and message widgets, see Resources). The basic widget for field input is Entry. It's easy to use, but if you've ever used Python's raw_input () or curses's. GETSTR (), you'll find that the techniques are slightly different. The Entry widget for TK does not return a value that can be allocated. Instead, it gets the argument to populate the Field object. For example, the following function allows the user to specify an input file.
Accept user Field input

Def getsource ():
 Get_window = tkinter.toplevel (root)
 get_window.title (' Source File? ')
 Tkinter.entry (Get_window, width=30,
 textvariable=source). Pack ()
 Tkinter.button (Get_window, text= "Change" ,
 command=lambda:update_specs ()). Pack ()

Here are a few things to watch out for. We created a new TopLevel widget and dialog box for this input, and specified the input field by creating a Entry widget with textvariable arguments. But wait a minute, there's one more thing!

The textvariable argument does not specify a simple string variable. Instead, it refers to a Stringvar object. In our example, the Init_vars () function called from Main () contains three rows.

Source = Tkinter.stringvar ()
source.set (' Txt2html.txt ')

This creates an object that applies to user input and assigns an initial value to it. The object is modified every time you make a change in the Entry widget that is linked to it. The Raw_input () style changes are made each time a keystroke is clicked in the Entry widget, rather than when the read is terminated.

To get the value of the user input, we use the. got () method of the Stringvar instance. For example:

source_string = Source.get ()

Conclusion

The techniques outlined here and the techniques we use in the full application source code should be enough to get you started with Tkinter programming. After a little practice you will find it easy to master. One advantage is that you can access the TK library in many languages other than Python, so most of the knowledge you learn with the Python Tkinter module can be applied to other languages.

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.