Cute python: TK in Python Program for beginners using the Python GUI library David Mertz Dr. Gnosis Software, Inc. President of 2000
content:
TK brief description start learning basic knowledge of basic knowledge from test applications Main () Function Application Geometric Graphics Manager menu Get User Enter Conclusion Reference About the author
David Mertz introduces the TK and Tkinter Packaging (Python's GUI) with source code samples and detailed descriptions. In order to make more convenient operation, he demonstrated the GUI transplant example of the TXT2HTML front-end program used in many articles. Of course, he thinks you will read its column regularly. :)
I would like to introduce you to the easiest way to start the GUI programming, which is to use Scriptics TK and Tkinter packaging. We will make a lot of comparison with the Curses library mentioned in "Curses programming in Python" in developerWorks. In addition to the CURSES implementation of the text console, the two libraries have an amazing interface. Before using any library, you need to basically understand the window and event loop and refer to the available widgets. (Good, good reference and appropriate amount of exercises.) As with the article about Curses, this article only discusses 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. References later in this article point to a collection of several higher-level user interface widgets, but you can do a lot with Tkinter itself, including the constructing your advanced widget. Learning Basic Tkinter modules will introduce TK's way of thinking, even if you continue to use a higher-level widget collection, this thinking is still important. TK brief description TK is the most closely related to TCL language, and the TCL language and TK are developed by John OUSTERHOUT. Although TK appeared as the X11 library in 1991, it was actually ported to each popular GUI from which time. (It is similar to Python with "standard" GUI's situation.) Now, most popular languages and many small languages have TK bindings (Tkinter modules). Before starting, I must admit: I am not a thin small and dry TK programming expert. In fact, most of my TK programming experience will start three days ago. The three days did not have no challenges, but in the end, I felt very well to master Tkinter. What I want to say here is that the TK and Tkinter wrappers are designed very well, easy to operate, and is just about the easiest introduction of GUI programming. From the test application we will use TXT2HTML, this file format conversion program used in many columns (see Refigu), as the test application. Although TXT2HTML can be run in several ways, the package here is to run TXT2HTML from the command line. The application runs in the form of a batch process and has a command line independent variable indicating all aspects of the conversion to be performed. (In the future, it is best to provide the user to provide the interactive selection screen option to boot the user to gradually select different conversion options and provide visual feedback from the selected option before performing the actual conversion.) TK_TXT2HTML is based on the drop-down menu and the nested submenu. The top menu. Next to a detailed implementation, it looks very similar to the CURSES version discussed in "Curses" in Python. Although TK can achieve more features with less code, it is obvious, TK_TXT2HTML and Curses_txt2HTML are very similar. For example, in TK, features such as menu can rely on built-in Tkinter class without having to write it from head. In addition to setting configuration options, the TK package also includes a scrolling help box with the TK Text widget (a "about" with the Message widget) and a historical window for TK dynamic geometry. Like most interactive applications, the encapsators accept certain user input with the TK Entry window widget. Let's take a look at the actual operation before further discussing the code.
Learning basic knowledge is actually, Tkinter programs need only three things: Minimal [Tkinter] Program Import Tkinter # Import The Tkinter Module
root = tkinter.tk () # Create a root window
Root.mainloop () # Create An Event Loop
This is a completely effective Tkinter program (don't mind it without actual use, because it does not even manages "Hello World"). The only thing that the program needs to do is to create some widgets that accommodate their root windows. After this, there is no need to further interfere with the programmer, and the ROOT .MAINLOOP () method of the program can handle all users interaction. Main () function now, let's take a look at TK_TXT2HTML.PY more realistic main () function. Note that I prefer to use John Grays's Import Tkinter statement, not from Tkinter Import (see his books listed in the reference). This is not because I am worried that the namespace interference (from ... Import statement usually warning), but because I want to express the Tkinter class; I don't want to take risks to confuse them with my own function and class). It is recommended that you do this, at least in 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, Side = tkinter.top)
Menu_frame.tk_menubar (file_menu (), Action_Menu (), Help_Menu ())
# - CREATE The History Frame (To BE Filled 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 = Tkinter.x, Side = Tkinter.bottom)
# First Put The Column Labels in A SUB-Frame
Left, label = tkinter.Left, Tkinter.label # Shortcut 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)
# t 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 Actually Do All That Stuff CREATED ABOVE
root.mainloop ()
There are a few things in this simple main () function to pay attention:
Each widget has a parent. Whenever a widget is created, the first self-variable created to the instance is a parent of the new window widget. If you have other widgets create an argument, they will pass them through the name. This feature of Python gives us great flexibility to specify or allow them to take default values. There are several widgets instances (FRAME) is global variables. They can be used to transfer variables between functions to maintain the local variables to maintain the theoretical purity of the code range, but it is too troublesome than its actual use. In addition, these basic UI elements emphasize such a fact that they can be used throughout the function. However, ensuring a good naming specification for your global variables. (Give you a warning in advance, Python people look annoyed Hungarian symbols.) After creating a widget, we call a geometric graphic manager to let TK know where to place widgets. TK has many magic in calculating detail information, especially when adjusting the window size or dynamically adding widgets. But in any case, you need to let TK know which to use. Apply geometric graphic manager TK to provide three geometric graphics managers: .pack () ,. grid () and .peck (). Although .Place () can be used for fine (in other words, very complex) control, but TK_TXT2HTML only uses two heads. Most of the time you will use .pack (). Of course, the .pack () method can be called without an argument. But if you do, the widget may end at some point of the display screen, and you may also want to provide some prompts for .pack (). The most important thing in these tips is the SIDE argument. Possible values are Left, Right, Top, and Bottom (Note that these are variables in the Tkinter namespace). Many magic from .pack () come from the fact that the widget can be nested. In addition, in addition to the container (which sometimes displays different types of boundaries), the Frame window widget is hard to do. In this way, several frames can be conveniently arranged in the desired direction, and then other widgets are added to each frame. They are arranged in the order of the .pack () method of the calling frame (and other widgets). Therefore, if the two widgets request Side = TOP, the first entry request is satisfied. TK_TXT2HTML is also occasionally used .Grid (). Grid Geometric Graphics Manager covers 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 fourth column of the third row. Calculate the total number of banks and total columns of the parent generation by viewing all the processes of the parent. Don't forget to apply geometric graphic manager for your own window widgets, so as not to regret when you can't see them on the screen. Menu tkinter can easily generate a menu. Although we use very simple example here, if you are willing, you can fill the menu with different fonts, graphics, checkboxes, and a variety of chic sub-generation widgets. In our example, the menu of TK_TXT2HTML is created with our rows we have seen above. Menu_frame.tk_menubar (file_menu (), Action_Menu (), Help_Menu ())
This trip may be some mysterious. Most of the required work is located 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
The drop-down menu is a MenuButton small window component that uses the MENU small window component as the child. .pack () (or .grid (), etc.) arrange menubutton in place. The Menu small window component adds an item with a .add_command () method. (Please pay attention to the strange allocation of the directory of Menubutton. Don't ask why, follow me and do this in your own code.) Get the user input below the example demonstration Label small window parts widget How to display the input (for some examples of the text and Message small window parts, see Resources). The basic small window component entered by the field is entry. It is easy to use, but if you used to use Python's Raw_Input () or Curses. GetStr (), you will find a slightly different skill. The TK's Entry small window component does not return the assignable value. Instead, it gets the argument to fill 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.TILE ('Source File?')
Tkinter.Entry (get_window, width = 30,
Textvariable = source) .pack ()
Tkinter.Button (get_window, text = "change",
Command = lambda: Update_specs ()). Pack ()
There are a few things to pay attention to here. We create a new TopLevel small window part and dialog for this input and specify the input field by creating an Entry small window component with the TextVariable argument. But wait, there is something! TextVariable arguments do 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 lines.
Source = tkinter.stringvar ()
Source.set ('TXT2HTML.TXT')
This creates an object that is suitable for user input and assigns an initial value. This object is immediately modified each time you change in the Entry small window component of the phase link. The Raw_INPUT () style changes each time you hit the key in the Entry small window component instead of reading termination. To get the value input, we use the StringVar instance. Get () method. E.g:
Source_string = source.get ()
Conclusion The techniques you will be described here and our skills used in the complete application source code should be enough to start Tkinter programming. You will find it not difficult to master after slightly practicing. There is a benefit that you can access the TK library through many languages other than Python, so you can apply to other languages using Python's Tkinter modules. References To get a good job, check the Tkinter resources of Python.org. Several small window components can save you time to construct complex UI. PMW (Python Mega Widgets) is fully written and widely used in the Python community with Python. Fredrik Lundh has written a Tkinter tutorial that is more detailed than this article. There are several print books worth seeing. The first is a good introduction to TK itself. The second book is specifically python, and there are many examples of using the PMW collection:
TCK / TK IN A Nutshell, Paul Raines and Jeff Tranter (O'Reilly, 1999) Python and Tkinter Programmingjohn E. Grayson (Manning, 2000) ActiveState recently created an excellent Python distribution, including Tkinter And other convenient packages and modules that are not available in most other issues. They also created an ActivePerl distribution for those who tend to other scripting languages. ) Rename Scriptics (TK maintor and founder). Please read these related articles written on David Mertz on developerWorks:
"Cute Python: Curses Programming" "Cute Python: My First Web-based Filter Agent" Read the article mentioned in this article.