Python Tkinter Hello,Tkinter

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.

每一个严肃的教程都会以一个“hello world”类型的例子开头,为了保持这个惯例我们要为你展示两个这样的例子。

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

首先,让我们看一个漂亮的最小版本:

Our First Tkinter Program (File: hello1.py)
from Tkinter import *

root = Tk()

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

root.mainloop()

Running the Example

To run the program, run the script as usual:

运行这个脚本:

$ python hello1.py

The following window appears.

会出现下面的窗口。

Running the program

To stop the program, just close the window.

想要停止这个窗口,关闭它就可以了。

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:

它包含所有的类、函数和Tk套件需要的物件。大多数情况下,可以简单的导入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选项去指定要显示的文本。

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方法。这个方法会根据给出的文本自动设置组件的大小并变得可视。总之,在进入Tkinter事情循环之前窗口不会出现。

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 pack method) and display updates. This also means that the application window will not appear before you enter the main loop.

在关闭 应用窗口之前程序都会等等事件。事件循环不单单操作来自用户(像鼠标点击和按键)或者窗口系统的事件,它同样操作来自于Tkinter自身的事件。在这些操作内是几何管理(由pack方法排列)和显示更新。这也意味着在进入main循环前应用窗口不会出现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值