Python图形用户界面

tkinter是Python中可用于构建GUI的众多工具集之一。

几乎所有真实的GUI都是以类和对象来建造的:他们讲模型、视图和控制器一起放到一个干净整洁的包(package)中。例如下面的计数器函数,其模型是Counter类的一个名为self.state的成员变量,其控制器是upClickquitClick方法。

from tkinter import *

class Counter:
    """A simple counter GUI using object-oriented programming."""

    def __init__(self, parent):
        """Create the GUI."""

        # Framework.
        self.parent = parent
        self.frame = Frame(parent)
        self.frame.pack()

        # Model.
        self.state = IntVar()
        self.state.set(1)

        # Label displaying current state.
        self.label = Label(self.frame, textvariable=self.state)
        self.label.pack()

        # Buttons to control application.
        self.up = Button(self.frame, text="up", command=self.upClick)
        self.up.pack(side="left")

        self.right = Button(self.frame, text="quit", command=self.quitClick)
        self.right.pack(side="left")

    def upClick(self):
        """Handle click on "up" button."""
        self.state.set(self.state.get() + 1)

    def quitClick(self):
        """Handle click on "quit" button."""
        self.parent.destroy()

if __name__ == "__main__":
    window = Tk()
    myapp = Counter(window)
    window.mainloop()

参考资料:
《Python编程实践》
《Practical Programming An Introduction to Computer Science Using Python》

文章导航