python基础-图形界面库

Python 支持多种图形界面的第三方库:TkwxWidgetsQtGTK

Python自带的库是支持Tk的Tkinter,使用Tkinter,无需安装任何包,就可以直接使用

内置的Tkinter封装了访问Tk的接口:

Tk是一个图形库,支持多个操作系统,使用Tcl语言开发;

Tk会调用操作系统提供的本地GUI接口,完成最终的GUI。

所以,代码只需要调用Tkinter提供的接口就可以了。

编写Hello World!

from Tkinter import *
#从Frame派生一个Application类,是所有Widget的父容器
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()
#每个Button、Label、输入框等,都是一个Widget。Frame则是可以容纳其他Widget的Widget,所有的Widget组合起来就是一棵树
    def createWidgets(self):
        self.helloLabel = Label(self, text='Hello, world!')
        self.helloLabel.pack()    #pack()方法把Widget加入到父容器中,并实现布局,grid()可以实现更复杂的布局
        self.quitButton = Button(self, text='Quit', command=self.quit)    #当Button被点击时,触发self.quit()使程序退出
        self.quitButton.pack()
#实例化Application,并启动消息循环
app = Application()
# 设置窗口标题:
app.master.title('Hello World')
# 主消息循环:
app.mainloop()

#GUI程序的主线程负责监听来自操作系统的消息,并依次处理每一条消息。因此,如果消息处理非常耗时,就需要在新线程中处理

 运行如图所示:

输入文本:

from Tkinter import *
import tkMessageBox

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.nameInput = Entry(self)
        self.nameInput.pack()
        self.alertButton = Button(self, text='Hello', command=self.hello)
        self.alertButton.pack()

    def hello(self):
        name = self.nameInput.get() or 'world'
        tkMessageBox.showinfo('Message', 'Hello, %s' % name)
#点击按钮时,触发hello(),通过self.nameInput.get()获得用户输入的文本后,使用tkMessageBox.showinfo()可以弹出消息对话框。

 

如图:

 

posted @ 2015-12-15 10:27  超超xc  Views(1639)  Comments(0Edit  收藏  举报
I suppose,were childrenonec.