Hello, Tkinter

But enough talk. Time to look at some code instead.

As you know, every serious tutorial should start with a “hello world”-type example. In this overview, we’ll show you not only one such example, but two.

First, let’s look at a pretty minimal version:

但是说的太多了,现在我们来看看代码

正如你所知道的,每一个严谨的教程都从hello world开始,现在我们从两个例子开始

第一个实例程序

#coding=utf-8
# hello.py
from Tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()

Running the Example运行这个程序

$ python hello1.py

停止程序只需要按x号

Details 分析代码的细节

We start by importing the Tkinter module. It contains all classes, functions and other things needed to work with the Tk toolkit. In most cases, you can simply import everything from Tkinter into your module’s namespace:

从引用这个 Tkinter 模块开始.它包含了所有需要使用的类, 方法,和其他的一些需要使用的事情.

在大多数的例子中,你可以简单的从tkinter引入到你的模块的命名空间中.

from Tkinter import *

To initialize Tkinter, we have to create a Tk root widget. This is an ordinary window, with a title bar and other decoration provided by your window manager. You should only create one root widget for each program, and it must be created before any other widgets.

初始化这个Tkinter, 我们好还需要Tk 工具控件.这是一个原始的窗口,带有一个标题和另一个由窗口控制器提供的装饰器.

你应该在每一个程序中仅仅创造一个根控件,而且必须在其他控件之前创建.

root = Tk()

Next, we create a Label widget as a child to the root window:

接下来我们要创造一个label 空间来作为跟窗口的子控件

w = Label(root, text="Hello, world!")
w.pack()

Label widget can display either text or an icon or other image. In this case, we use the text option to specify which text to display.

这个Label控件可以展示text文本和icon图标或者其他的图片.

在这一个例子中,我们使用了text文本的选项来具体说明哪一个文本展示.

Next, we call the pack method on this widget. This tells it to size itself to fit the given text, and make itself visible. However, the window won’t appear until we’ve entered the Tkinter event loop:

接下来用这个控件调用pack() 方法. 这告诉它去定义它自身的大小来适应这个给出的文本.并且使其可见.

无论适合,窗口在我们调用 事件循环 mainloop() 方法之前是不能体现出来的

root.mainloop()

The program will stay in the event loop until we close the window. The event loop doesn’t only handle events from the user (such as mouse clicks and key presses) or the windowing system (such as redraw events and window configuration messages), it also handle operations queued by Tkinter itself. Among these operations are geometry management (queued by the packmethod) and display updates. This also means that the application window will not appear before you enter the main loop.

这个程序会停留在事件循环中知道我们关闭了这个窗口,这个事件循环不仅仅会接管用户或者窗口系统的点击输入选项配置等等事件.它也会接管一些tkinter本身的序列的操作.

在许多的操作中比如绝对位置管理和显示更新有新的内容出现更新.这也意味着这个应用程序不会在进入这个事件主循环之前进行所谓的显示

猜你喜欢

转载自blog.csdn.net/CarlBenjamin/article/details/82953457