Tkinter-Python的GUI包初体验

Python的GUI包有不少,easyGUI可能更加适合新手,可是Tkinter包做为一个官方自带的包,功能强大,也比较易于上手。本文将对Tkinter的使用有一个初步的讲解。编程

下面是Python官网关于Tkinter的介绍ide

Tkinter is Python's de-facto standard GUI (Graphical User Interface) package. It is a thin object-oriented layer on top of Tcl/Tkoop

Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one. CameronLaird calls the yearly decision to keep TkInter "one of the minor traditions of the Python world."ui

因为Tkinter是内置的模块,因此咱们能够直接引用code

import tkinter

学编程的都知道有个门路:入门从Hello World写起。那么让咱们先看一下官方上的入门程序:事件

import tkinter
from tkinter.constants import *
tk = tkinter.Tk()
frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
frame.pack(fill=BOTH,expand=1)
label = tkinter.Label(frame, text="Hello, World")
label.pack(fill=X, expand=1)
button = tkinter.Button(frame,text="Exit",command=tk.destroy)
button.pack(side=BOTTOM)
tk.mainloop()

在Python终端中运行,就会有下面的结果!ci

第一个Tkinter程序

这样,第一个Hello World程序就运行完成了it

固然,若是上面的代码你不是一块儿复制进终端,而是在IDLE中,经过交互式界面一行一行输入,便会发如今最后一句tk.mainloop()这个语句执行以前,窗体并无生成。但这句话一执行以后,窗体就生成了,一切都能正常运行。这是为何呢?为何执行tk = tkinter.Tk()这个语句时,就没有直接生成一个窗体呢?io

其实,tk.mainloop()的做用是重建窗体,而且开始检测事件。而以前的语句就是为创建窗体循环作准备。GUI编程与控制台编程有点不同,它至关因而个死循环,只不过在检测到退出的事件,或者整个窗体被销毁,才会结束。入门

那么最基础的HelloWorld程序就到这里结束了,关于这里面的tk窗体,frame,label,button组件,还有pack等方法将在以后介绍。

相关文章
相关标签/搜索