Day-16: 图形界面

  Python支持多种图形界面,有:第三方库有Tk、wxWidgets、Qt、GTK等。

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

  在Python中使用函数调用Tkinter的接口,然后Tk会调用操作系统提供的本地GUI接口,完成最终的GUI。

  编写一个简单的GUI:

from Tkinter import *

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

    def createWidgets(self):
        self.helloLabel = Label(self, text='Hello, world!')
        self.helloLabel.pack()
        self.quitButton = Button(self, text='Quit', command=self.quit)
        self.quitButton.pack()
app = Application()
# 设置窗口标题:
app.master.title('Hello World')
# 主消息循环:
app.mainloop()

  在GUI中,每一个按钮、标签、输入框都是一个Widget。Frame是最大的Widget,它可以容纳其他的Widget。

  pack()方法是将已经创建好的Widget添加到父容器中,它是最简单的布局,grid()可以实现相对复杂的布局。

  在creatWidgets()方法中,创建的Button被点击时,触发内部的命令self.quit(),使程序退出。

  还可以增加输入文本的文本框:

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()获得用户输入的文本后,使用txMessageBox.showinfo()可以弹出消息对话框。

 注:本文为学习廖雪峰Python入门整理后的笔记

原文地址:https://www.cnblogs.com/likely-kan/p/7542052.html