Pythongui Programming-tkinter

Source: Internet
Author: User
Tags pack

Graphical user interface (G raphical U ser I Nterface,gui) programming

Versions below the Python2.0 level are called tkinter,python3.0 renamed Tkinter

Tkinter module: Adding Tk to the application
So what do you need to do to make Tkinter a part of the app? First, applications that already exist are not required. If you want, you can create a pure GUI program, but a program with no interesting underlying features will not be useful.
The following 5 main steps are required to get the GUI program up and running.

1. Import the Tkinter module (or from tkinter import *).
2. Creates a top-level window object that holds the entire GUI application.
3. Build all of the GUI components (and their functions) above the top-level window object (or "where").
4. These GUI components are connected by the underlying application code.
5. Enter the main event loop.
The first step is trivial: all GUI programs that use Tkinter must import the Tkinter module.

Windows and controls
In GUI programming, the top-level Root window object contains all the small window objects that make up the GUI application. They can be text labels, buttons, list boxes, and so on. These stand-alone GUI components are called controls. So when we say creating a top-level window, it just means that we need a place to put all the controls. In Python, the following statements are generally written.
  top = Tkinter. TK () # or just TK () with ' from Tkinter import * '
The object returned by tkinter.tk () is often referred to as the root window, which is why some applications use root instead of top to refer to it. Top-level windows are those that are displayed independently in the app. There can be multiple top-level windows in a GUI program, but only one of them is the root window. You can choose to have all of the controls designed first, add functionality, or add functionality as you design the controls (which means that steps 3rd and 4th in the previous step are mixed).
The control can exist independently or as a container. If a control contains other controls, it can be thought of as the parent control of those controls. Correspondingly, if a control is contained by another control, it is considered a child control of that control, and the parent control is the next container control that encloses it directly.
Typically, a control has some related behaviors, such as pressing a button, writing text to a text box, and so on. These user behaviors are called events, and the GUI's response to such events is called callbacks.

When all the controls are placed, you can let the app enter the infinite main loop described above. In Tkinter, the code is shown below.
  Tkinter.mainloop ()
Typically this is the last piece of code that the program runs. When the main loop is entered, the GUI begins to take over the execution of the program from here. All other behaviors are handled through callbacks, even exiting the app. When you select the File menu and click the Exit menu option, or close the window directly, a callback function is called to end the GUI application.

Top-level window: Tkinter. Tk ()
The object is created in Tkinter using the TK class, and then instantiated as follows:
>>> Import Tkinter
>>> top = Tkinter. Tk ()
In this window, you can place individual controls, or you can piece together multiple components to form GUI programs.

Some of the commonly used TK controls

The default value is your best friend.

The GUI exploited the default parameters of Python because there are many default behaviors in the Tkinter controls. Unless you are very aware of the use of each of the available options for each of the controls you are using, it is best to only care about the parameters you want to set, and let the system handle the remaining parameters. These default values are carefully selected. Even if you don't provide these values, don't worry about the application's display on the screen. As a basic rule, the program is created by a series of optimized default parameters and should only be used if you know how to customize your control precisely.

Label Control

Import tkinter# contains a label, Labeltop = Tkinter. Tk ()  # Creates a top-level window label = Tkinter. Label (Top, text= "Hello world!")  # Displays the contained file or picture Label.pack ()  # Display Control Tkinter.mainloop ()  # callback function for running this GUI application

Output effect

Button Control

Import tkinter# contains a button, Buttontop = Tkinter. Tk () quit = Tkinter. button (top, text= "Hello world!", command=top.quit)  # Here is to create a function button (quit) instead of a label quit.pack ()  # Display Control Tkinter.mainloop ()  # run this GUI program

Output effect

Label and Button controls

Combines the above two cases with both a label label and button

Import tkinter# includes a label and a button, label, Buttontop = Tkinter. Tk () Hello = Tkinter. Label (top, text= "Hello world!"). Pack () quit = Tkinter. button (top, text= "Quit", Command=top.quit, bg= ' Red ', fg= ' white ') # text text, command press button function, BG background color, FG font color, Quit default mouse bounces off GUI program Quit.pack (fill=tkinter. X, expand=1) # Pack Management and display controls, fill tells pack to occupy the remaining horizontal space, expand guide it to fill the entire horizontal visual space Tkinter.mainloop ()

Output effect

Label, Button, and scale controls

Import tkinter# callback function, the function is attached to the scale control # when the slider of the scale control moves, the function is activated to adjust the size of the text in the Label control. def resize (ev=none):    label.config (font= ' Helvetica-%d bold '% Scale.get ()) top = Tkinter. Tk () # Top-level window top.geometry (' 250x150 ') # set window Size label = Tkinter. Label (top, text= "Hello world!", font= "Helvetica-10 Bold") Label.pack (Fill=tkinter. Y, expand=1) scale = Tkinter. Scale (top, from_=10, to=40, Orient=tkinter. Horizontal, Command=resize) # From_ The smallest size, to the largest size, orient=tkinter. Horizontal text box, horizontal scroll bar, Scale.set  # Sets the initial value size Scale.pack (fill=tkinter. X, expand=1) quit = Tkinter. button (top, text= "QUIT", Command=top.quit, activeforeground= ' white ', activebackground= ' Red ') # Activeforeground Mouse bounce font changed to white, activebackground mouse bounce background Red quit.pack () Tkinter.mainloop ()

Output effect

Partial Function Application Example

In this example, we'll use traffic signs to demonstrate that we're going to try to create a text version of the Signpost and differentiate it based on the flag type, such as severity, warning, notification, etc. (like the log level). The flag type determines the color scheme at the time of creation. For example, a severity flag is a white-bottom red character, and a warning level flag is a black word on a yellow bottom, and a notification (that is, a standard level) is a black word on a white background. Here, the "Do Not Enter" and "wrong" flags belong to the severity level, "Merging traffic" and "railroad Crossing" belong to the warning level, while the "Speed Limit" and "one" are the standard levels.

Import functoolsimport tkinterimport tkinter.messagebox # message box warn = ' warn ' crit = ' crit ' Regu = ' regu ' signs = {' Do not ente R ': Crit, ' Railroad crossing ': WARN, ' 55\nspeed limit ': Regu, ' wrong ': crit, ' merging   Traffic ': WARN, ' one ': regu,}CRITCB = lambda:tkinter.messagebox.showerror (' Error ', ' Error Button pressed! ') # lambda expression, defines several functions ... return value WARNCB = lambda:tkinter.messagebox.showwarning (' Warning ', ' Warning Button pressed! ') INFOCB = lambda:tkinter.messagebox.showinfo (' info ', ' info Button pressed! ') top = Tkinter. Tk () top.title ("Road signs") # Sets the title Tkinter. button (top, text= ' QUIT ', command=top.quit, bg= ' Red ', fg= ' White '). Pack () # Create a QUIT button # Templated button class and Root window top# each call My_ button, he invokes the button class (Tkinter. The button () creates one, # and takes top as its first parameter, we freeze it to My_buttonmy_button = Functools.partial (tkinter. Button, top) Crit_button = Functools.partial (My_button, COMMAND=CRITCB, bg= ' white ', fg= ' red ') Warn_button = Functools.partial (My_button, COMMAND=WARNCB, bg= ' #b8860b ') Regu_button = Functools.partial (My_button, COMMAND=INFOCB, bg= ' White ') # When the user creates a critical type of button Crit_button (for example by calling Crit_ button ()), # It calls the my_button,# that contains the appropriate button callback function, foreground color, and background colors, or uses top, callback function, and color parameters to call Buttonfor eachsign in signs: # eachsign = Key Signtype = signs[eachsign] # gets value # Signtype = = value cmd = '%s_button (text=%r%s). Pack (Fill=tkinter. x,expand=true) '% (Signtype, Eachsign, '. Upper () ' if s    Igntype = = Crit Else '. Title () ') # If the output is a severity level, we use upper () to change him to uppercase # print (cmd) eval (cmd) # each button is instantiated with the eval () function # because the cmd output is a string, eval () evaluates the string str as a valid expression and returns the result of the calculation top.mainloop ()

Output effect

Pythongui Programming-tkinter

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.