A brief introduction to the GUI programming using TK under Python

Source: Internet
Author: User
Tags wrappers
I want to introduce you to the simplest way to start GUI programming, using Scriptics's 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 a text console and TK implementing a GUI, the two libraries have surprisingly similar interfaces. Before using any of the libraries, you need to have a basic understanding of the window and event loops and refer to the available widgets. (Good, good reference and proper exercise.) )

As with articles on curses, this article discusses only the characteristics of Tkinter itself. Since many Python distributions come with 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 widgets, but you can do many things with Tkinter itself, including building your own advanced widgets. Learning the basic Tkinter module will introduce you to TK's mindset, which is still important even if you continue to use the more advanced Widgets collection.
TK Brief description

TK is the most closely related and widely used graphics library in Tcl, and the Tcl language and TK are developed by John Ousterhout. Although TK appeared as a X11 library in 1991, it was actually transplanted 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 thin, withered TK programmer. 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 felt a good grasp of Tkinter. What I'm saying here is that the TK and Tkinter wrappers are designed to be very good, user-friendly, and simply a simple introduction to GUI programming.

Start with the test application

We will use txt2html, the wrapper for the file format translator, used in many previous columns (see Resources) as the test application. Although you can run txt2html in several ways, the wrapper here is running txt2html from the command line. The application runs in the form of a batch process with command-line arguments that indicate the various aspects of the transformation to be performed. (Later, it's a good idea to provide the user with interactive selection screen options to guide the user through a gradual selection of different conversion options and provide visual feedback on the selected options before performing the actual conversion.) )

Tk_txt2html is based on the top menu with drop-down menus and nested submenus. There is a detailed implementation note next to it, which looks very similar to the Curses version discussed in "Curses Programming in Python". Although TK can do more with less code, it is clear that tk_txt2html and curses_txt2html are very similar. For example, in TK, features like menus can be implemented with built-in Tkinter classes 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 a Message widget) and a History window for TK dynamic geometry management. Like most interactive applications, the wrapper accepts some user input with the Entry widget of TK.

Before we discuss the code further, let's 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 moduleroot = tkinter.tk () # Create a root windowroot.mainloop () # Create an event loop

This is a completely effective Tkinter program (don't mind that it's not actually useful because it doesn't even manage "Hello World"). The only thing the program needs to do is create some widgets that hold its root window. After this enhancement, no further interference from the programmer is required, and the program's root. Mainloop () method call can handle all user interactions.

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 the From Tkinter import (see his books listed in resources). This is not because I'm 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 () #--Crea Te the menu frame, and menus to the menu frame Menu_frame = tkinter.frame (root) menu_frame.pack (fill=tkinter.x, Side=tkint Er. TOP) Menu_frame.tk_menubar (File_menu (), Action_menu (), Help_menu ()) #--Create The history frame for filled in during R Untime) 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=tkinter.x, Side=tkinte R.bottom) # First put the column labels in a sub-frame left, Label = Tkinter.left, Tkinter.label # shortcut names Label_li NE = 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_fram e) info_line.pack (Side=tkinter.top, padx=2, Pady=1) update_specs () #--Finally, let's actually do all, stuff created a Bove 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 arguments, they are passed by name. This feature of Python gives us great flexibility to specify options or allow them to take default values.
There are several widgets instances (Frame) that are global variables. Variables can be passed between functions to make them local variables to maintain the theoretical purity of the code scope, but it is cumbersome compared to its actual usefulness. In addition, making these basic UI elements global emphasizes the fact that they can be used throughout the function. However, be sure to use a good naming convention for your global variables. (a warning is given beforehand, and Python people seem to hate the Hungarian symbol.) )
After creating the widgets, we call a geometry manager to let TK know where to place the widgets. TK has a lot of magic when it comes to calculating details, especially when resizing windows or dynamically adding widgets. But in any case, you need to let TK know which mantra to use.

Apply Geometry Manager

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

Of course, you can call the. Pack () method without arguments. However, if you do that, the widget may end up somewhere on the display screen, and you may 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).

Many of the magic of. Pack () comes from the fact that widgets can be nested. In particular, the Frame widget has little to do except as a container for other widgets, which sometimes show 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 in the order of the. Pack () methods that call the framework (and other widgets). Therefore, if the two widgets request Side=top, the first entry request is satisfied.

Tk_txt2html also occasionally uses. Grid (). The grid Geometry Manager overwrites the parent widget with a visual coordinate line. When the widget calls. Grid (Row=3, column=4), it requests its parent to place it on the fourth column of the third row. Calculates the total number of rows and columns of the parent by looking at the requests 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. While we're using a very simple example here, if you want, you can also populate the menu with different fonts, graphics, check boxes, and a variety of chic descendant widgets. In our example, tk_txt2html's menus are all created with the lines we see above.

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

The line itself may be a bit mysterious. Most of the work that must be done is in a function called *_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

The drop-down menu is a small window widget that menubutton the menu widget as a descendant: Pack () (or. Grid (), etc.) arranges the Menubutton in the appropriate location. The Menu widget uses the. Add_command () method to add an item. (Note the strange assignment above for the Menubutton directory.) Don't ask why, follow me and do it in your own code. )


Get user input

The following example shows how the Label small widget widget displays input (see Resources for a complete resource for some examples of the Text and Message small widgets). The Basic small window widget for field input is Entry. It's easy to use, but if you've ever used Python's raw_input () or curses. Getstr (), you'll find the techniques slightly different. TK's Entry small widgets do not return assignable values. Instead, it gets the arguments 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 an input field by creating a small Entry widget with textvariable arguments. But wait a minute, there's another 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 is appropriate for user input and assigns an initial value to it. The object is immediately modified every time it is changed in the Entry widget with which it is linked. Changes to the Raw_input () style are made every time the keystrokes are clicked in the Entry widget, rather than when the read terminates.

To get the values entered by the user, we use the. Get () 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 benefit is that the TK library can be accessed in many languages other than Python, so most of the knowledge you learn with Python's 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.