The real example of Python Tkinter __python

Source: Internet
Author: User
Regardless of the conventional approach, let's try a lightweight and practical example. It will give you an idea of the initial feeling behind the TK program.
DesignThe example we use is a simple GUI tool that converts a number in a unit of foot into a metric unit number equal to it. If we describe it briefly, it should look like this: it looks like we need a short text input widget that allows us to enter a number in a foot unit and a ' Calculate ' button, use it to get the input of the foot number, perform the calculation, and then put the calculated metric numeric results in the position below the input text box.  Of course, we also need three static tags ("Feet", "is equivalent" and "Meters") to help us point out how to use the interface. The following is the Python code that created the program:
From tkinter Import * Tkinter import TTK
def calculate (*args): Try:value = float (Feet.get ()) Meters.set ((0.3048 * value * 10000.0 + 0.5)/10000 .0) except Valueerror:pass root = Tk () root.title ("Feet to Meters")
Mainframe = TTK. Frame (Root, padding= "3 3") Mainframe.grid (column=0, row=0, sticky= (N, W, E, S)) mainframe.columnconfigure (0, weight= 1) mainframe.rowconfigure (0, Weight=1)
Feet = Stringvar () meters = Stringvar ()
Feet_entry = TTK. Entry (Mainframe, width=7, Textvariable=feet) Feet_entry.grid (column=2, Row=1, sticky= (W, E))
Ttk. Label (mainframe, textvariable=meters). Grid (column=2, row=2, sticky= (W, E)) TTK. button (mainframe, text= "Calculate", command=calculate). Grid (Column=3, row=3, Sticky=w)
Ttk. Label (Mainframe, text= "feet"). Grid (Column=3, Row=1, sticky=w) TTK. Label (Mainframe, text= "is equivalent to"). Grid (Column=1, row=2, sticky=e) TTK. Label (mainframe, text= "meters"). Grid (Column=3, row=2, Sticky=w)
For child in Mainframe.winfo_children (): Child.grid_configure (padx=5, pady=5)
Feet_entry.focus () root.bind (' <Return> ', calculate)
Root.mainloop ()
The final user interface:
Code-style hints: in every language, including this tutorial, there are a variety of alternative writing styles and conventions to help us decide how to use variables and function names, processes, functional or object-oriented styles, and so on. Since this tutorial focuses on TK, it will be as simple as possible, typically using a very straightforward code style rather than focusing on our code in terms of processes, modules, objects, classes, and so on. There may be many, you will see in many examples will have the same object name, variable name, and so on.
step-by-Step commentaryFrom tkinter Import * Tkinter Import TTK These two lines tell Python that our program requires two modules. The first, ' Tkinter ', is a standard module that binds TK, and when it is loaded it will let the TK libraries that exist in your system load. The second, "TTK," is the binding of the new parts in Python and Tk8.5 versions. (Buttons, text boxes and the like are called parts) Tip: Note that we've imported all of this from the Tkinter module, so we can call the Tkinter function without the prefix, which is the standard calling method. However, since we only import the TTK itself, we need to add a prefix when we call the TTK intrinsic function. For example, call ' Entry (...) ' function that will reference the Tkinter module to your function, and only use ' TTK. Entry (...) ' In order to refer to TTK module functions. As you will see, some functions are defined in these two modules, and sometimes you may need both. Depending on the content, use TTK to invoke the device here, and use that style in the tutorial. Update: If you are migrating from the old version to the new version, one thing you'll find is that the name of the Tkinter module is lowercase. For example, "Tkinter" is not "Tkinter", which is changed from Python3.0.
root = Tk () root.title ("Feet to Meters") mainframe = TTK. Frame (Root, padding= "3 3") Mainframe.grid (column=0, row=0, sticky= (N, W, E, S)) mainframe.columnconfigure (0, weight= 1) mainframe.rowconfigure (0, Weight=1) only for reference: Yes, the "Calculate" function appears before. We'll describe it later, but include it in the program as it approaches the beginning, because other programs need to be referenced. These lines of code establish the main window, given the name "Feet to Meters". Next, we create a frame widget that controls all the controls on our user interface and places them on the main window. "Columnconfigure"/"Rowconfigure" simply tells TK that if the main window changes size, the frame should extend to the rest of the space. for reference only: Strictly speaking, we can put the other parts of the interface directly as the main window, without the need for framework intervention. However, the main window itself is not part of the scenario part, so its background color does not match the part of the solution that we are going to put in, and uses a "scenario" frame part to control the content to ensure the background color is correct.
Feet = Stringvar () meters = Stringvar () Feet_entry = TTK. Entry (Mainframe, width=7, Textvariable=feet) Feet_entry.grid (column=2, Row=1, sticky= (W, E)) TTK. Label (mainframe, textvariable=meters). Grid (column=2, row=2, sticky= (W, E)) TTK. button (mainframe, text= "Calculate", command=calculate). Grid (Column=3, row=3, Sticky=w) The above code creates the main three controls for our program: an input box for entering a foot number, a label label to place the metric result number, and a button to perform the calculation from the operation. For each of these three controls, we need to do two things: Create the controls themselves, and put them into the interface. The Content window we created is an instance of the TK scenario part class, which is the "child" of this instance (which should be translated as a subclass). As we create them, we give them the options that they determine. For example, the width of the input box, the text on the button, and so on. The input boxes and tags are all picked up as a magical "textvariable (text variable)", and we'll see how it is done in a moment. If these controls are created, they are not automatically displayed in the interface, because TK does not know how you want to place them relative to other controls. This is what the "grid" part does. Remember our application's layout grid, we place controls in different columns (1,2 or 3) and rows (1, 2, and 3). The "sticky" option indicates that by using the compass is the azimuth, how the control will be emitted in a grid unit, for example, "W" (west) means to position the control to the left of the cell, "we" means to position the control from the left to the right (the equivalent of the control from left to right), and so on. West-east
Ttk. Label (Mainframe, text= "feet"). Grid (Column=3, Row=1, sticky=w) TTK. Label (Mainframe, text= "is equivalent to"). Grid (Column=1, row=2, sticky=e) TTK. Label (mainframe, text= "meters"). Grid (Column=3, row=2, sticky=w) The above three lines of code do exactly the same thing with the three static text label controls in our interface: they were created, and placed in the appropriate grid position on the interface.
For child in Mainframe.winfo_children (): Child.grid_configure (padx=5, pady=5) Feet_entry.focus () Root.bind (' < Return> ', calculate] above three lines of code make our interface look friendlier. The first line checks all child controls within the frame and adds a small distance around each control, so they don't look so crowded. When we first put the controls into the interface, we can add these options to every "grid" call, but this is just a nice shortcut. The second line tells TK to shift attention to our input box, which means that at the beginning, the cursor defaults to the input frame area, so the user doesn't have to click it first when they enter. The third line tells TK that if the user presses the ENTER key, the calculation segment is invoked, as is the case when the calculation button is clicked.
def calculate (*args): Try:value = float (Feet.get ()) Meters.set ((0.3048 * value * 10000.0 + 0.5)/10000 .0) Except Valueerror:pass Here we define the calculation program, which is invoked when the user clicks the calculation button or presses the ENTER key. It performs the conversion from feet to meters, gets the input foot number from the input box, and places the result in the label control. Say what. It doesn't look like what we've done with these controls. This is how we define the Magic "textvariable" option when we create the control. We define the global variable "feet" for the input box as textvariable, i.e., whenever the input changes, TK automatically updates the global variable "feet". Similarly, if we explicitly change the value of a textvariable associated with a control (as we do with the "Meters" that is linked to a label control), the control is automatically updated with the contents of the current variable. Very flexible.
Root.mainloop () This last line tells TK to let the event loop, so that all things run.
Forgotten what. There are some that are worth checking and we are not included in the TK program. For example: • We did not consider the change of the parties when the interface was redrawn • We did not consider the evaluation of sending event messages, capture monitoring, or handle events in each space • We didn't provide more options when we created the control; The default seems to have been a lot of attention, and we just changed the display text on the button. We don't write complex code to get and set the values of simple controls, we just link them to variables we don't consider what happens when the user closes the window or changes the window size · We didn't write extra code to make it work across the platform.
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.