PythonGUI programming-tkinter, pythongui-tkinter

Source: Internet
Author: User

PythonGUI programming-tkinter, pythongui-tkinter

Graphical User Interface (G raphical U ser I nterface, GUI) Programming

The versions below Python2.0 are called Tkinter, and Python3.0 is renamed tkinter.

Tkinter module: Add Tk to Application
So what do you need to do to make tkinter a part of the application? First, existing applications are not necessary. If you want to, you can create a pure GUI program, but programs with no underlying functions that interest you will not be of any use.
The following five main steps are required to start and run the GUI program.

1. import the tkinter module (or from tkinter import *).
2. Create a top-level window object to accommodate the entire GUI application.
3. Build all GUI components (and functions) above the top-level window object (or "in it ).
4. Connect these GUI components through 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 constitute the GUI application. They may be text labels, buttons, and lists. These independent GUI components are called controls. Therefore, when we create a top-level window, we only need a place to place all the controls. In Python, it is generally written as the following statement.
  Top = tkinter. Tk () # or just Tk () with "from Tkinter import *"
Objects returned by Tkinter. Tk () are usually called root windows, which is why some applications use root instead of top. Top-level windows are those that are separately displayed in the application. GUI programs can have multiple top-level windows, but only one of them is the root window. You can choose to design all the controls before adding functions. You can also design the controls while adding functions (this means that steps 3rd and 4th in the above steps will be mixed up ).
Controls can exist independently or as containers. If a control contains other controls, it can be considered as the parent controls of those controls. Correspondingly, if a control is contained by another control, it is considered as the Child control of the control, and the parent control is the container control directly surrounded by it.
Normally, the control has some related behaviors, such as pressing a button and writing text into a text box. These user behaviors are called events, while GUI responses to such events are called callbacks.

After all the controls are placed, the application can enter the aforementioned infinite master loop. In tkinter, the Code is as follows.
  Tkinter. mainloop ()
Generally, this is the last piece of code to run the program. After entering the main loop, the GUI starts to take over program execution. All other actions are handled through callback, or even exit the application. When you select the File menu, 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 ()
This object is created using the Tk class in tkinter and then instantiated as follows:
>>> Import tkinter
>>> Top = tkinter. Tk ()
In this window, you can place independent controls or splice multiple components to form a GUI program.

 

Some common Tk controls

 

 

The default value is your best friend.

GUI development utilizes Python's default parameters because Tkinter controls have many default behaviors. Unless you are very clear about the usage of each available option for each control you are using, it is best to focus only on the parameters you want to set and let the system process the remaining parameters. These default values are carefully selected. Even if these values are not provided, you don't have to worry about the display of the application on the screen. As a basic rule, a program is created by a series of optimized default parameters. It should be used only when you know how to precisely customize your control.

Label Control

Import tkinter # contains a label, Labeltop = tkinter. Tk () # create a top-level window Label = tkinter. label (top, text = "Hello World! ") # Display included files or images label. pack () # display control tkinter. mainloop () # callback function, used to run this GUI application

Output result

 

Button Control

Import tkinter # contains a Button, Buttontop = tkinter. Tk () quit = tkinter. Button (top, text = "hello world! ", Command = top. quit) # create a function button (quit), instead of the tag quit. pack () # display control tkinter. mainloop () # Run this GUI Program

Output result

 

Label and Button controls

Combined with the above two cases, including both Label labels and Button buttons

Import tkinter # contains the Label and button, and the Label and 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, the function of pressing the button by command, bg background color, and fg font color, by default, quit pops up to close the quit GUI program. pack (fill = tkinter. x, expand = 1) # pack management and display controls, fill tells the pack to occupy the remaining horizontal space, and expand guides it to fill the entire horizontal visible space tkinter. mainloop ()

Output result

 

Label, Button, and Scale controls

Import tkinter # callback function, which is attached to the Scale control # When the slider of the Scale Control moves, this function is activated to adjust the text size 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 the 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 _ minimum size, to maximum size, orient = tkinter. HORIZONTAL text box, HORIZONTAL scroll bar, scale. set (10) # set the initial value scale. pack (fill = tkinter. x, expand = 1) quit = tkinter. button (top, text = "QUIT", command = top. quit, activeforeground = 'white', activebackground = 'red') # change the font of activeforeground to white, and change the background to red quit. pack () tkinter. mainloop ()

Output result

  Partial function application example

In this example, we will use traffic roadmap for demonstration. In this application, we will try to create a text version of the roadmap and distinguish it based on the logo type, for example, severe, warning, and notification (just like the log level ). The flag type determines the color scheme at creation. For example, the Severity Level mark is the white-bottom red letter, the warning level mark is the yellow-bottom black word, and the notification (standard level) mark is the white-bottom black word. Here, the "Do Not Enter" and "Wrong Way" Logos belong to the severity level, while "Merging Traffic" and "Railroad Crossing" belong to the warning level, "Speed Limit" and "One Way" belong to the standard level.

Import functoolsimport tkinterimport tkinter. messagebox # message box WARN = 'warn' CRIT = 'crit' REGU = 'regu' SIGNS = {'do not enter': crit, 'railroad crossing': warn, '55 \ nspeed limit ': REGU, 'wrong way': CRIT, 'merging traffic': WARN, 'one way': REGU,} critCB = lambda: tkinter. messagebox. showerror ('error', 'error Button Pressed! ') # Lambda expression, which 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") # Set 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 time my_button is called, it will call the Button class (tkinter. button () will create a Button), # use top as its first parameter, and we will freeze it as 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 a user creates a severe type of Button crit_button (for example, by calling crit_button ()), # It will call the my_button containing the appropriate button callback function, foreground color and background color, # or use the top, callback function, and color parameters to call Buttonfor eachsign in SIGNS: # eachsign = key signtype = SIGNS [eachsign] # obtain value # signtype = value cmd = '% s_button (text = % r % s ). pack (fill = tkinter. x, expand = True) '% (signtype, eachsign ,'. upper () 'if signtype = CRIT else '. title () ') # If the output is of a severity level, we use upper () to change it to uppercase # print (cmd) eval (cmd) # Each button will pass eval () function instantiation # Because cmd outputs a string, eval () uses the string str as a valid expression to evaluate the value and return the calculation result top. mainloop ()

Output result

 

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.