Recently learned Python has a period of time, but also wrote a number of small programs, but mainly are command line execution, has been trying to learn the GUI, considering the simplicity of TK, but also to meet the requirements of general procedures, decided to learn the next tkinter, ready to spend some time reading Python Tkinter The official introduction, and then write some small programs on their own. The following will be the official introduction of Tkinter in combination with their own understanding of translation into Chinese, but also by the way deepen their understanding.
Our first Python program
From tkinter import * #导入Tkinter模块
root = Tk () #创建一个根窗口, the rest of the controls are above this window
w = Label (Root, text= "Hello, world! ") #创建一个Label控件, specifies the root window created by its parent control bit, and displays the Hello worl!
on the label W.pack () #显示label控件, the Pack method makes the label display and automatically adjusts the size based on the text content
Root.mainloop () #让根窗口进入事件循环
run the program in the following way
$ python hello1.py
The following results will appear
Program Explanation:
1. We first import the Tkinter module, which contains everything we need to use Tkinter related functions, classes, and other related things.
From Tkinter Import *
This is the way to import everything, but it can also cause a contamination of the namespace.
2. In order to initialize Tkinter, we need to create a root control first. He is an ordinary window that contains a title bar and other decorations provided by the window manager.
root = Tk ()
You can create only one root control for each program, and it must be created before other controls are created.
3. Next we create a child control of the Label control seat root window.
W = Label (Root, text= "Hello, world!")
W.pack ()
The Label control can display text/bitmaps/images. In this example, we specify the text we want to display using the text option.
Next, we use the pack method on the Label control, which lets the label automatically resize itself according to the text and make itself visible.
In practice, however, the window does not appear unless we let tkinter into the event loop.
Root.mainloop ()
So the program will stay in the event loop until we close the window. The event loop not only handles requests from a user (such as clicking a mouse, pressing a button) or a window System (Tkinter), but also handles operations from within the inside of the operation. All of these operations are managed and updated through a geometric layout. In other words, the application window does not appear before you enter the event loop.