廖雪峰python学习笔记之使用Tkinter进行GUI编程

在网上看了一遭,发现用tkinter写GUI也是一种图方便的做法,基本的都能实现,但是美观,速度你就不要强求了,还是用Qt的人多一些,我一直也不太理解GUI的代码为什么这么写,但是照猫画虎也能实现,所以暂时就不深究了。

明确什么是Widget

在GUI中,每个Button、Label、输入框等,都是一个Widget。Frame则是可以容纳其他Widget的Widget,所有的Widget组合起来就是一棵树。

举个栗子

实现功能:用户输入文本,然后点按钮后,弹出消息对话框 ‘hello,xxx’

from tkinter import *
import tkinter.messagebox as messagebox

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        # pack()方法把Widget加入到父容器中,并实现布局。
        # pack()是最简单的布局,grid()可以实现更复杂的布局。
        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):
        # 通过self.nameInput.get()获得用户输入的文本后
        name = self.nameInput.get() or 'world'
        messagebox.showinfo('Message', 'Hello, %s' % name)

app = Application()
# 设置窗口标题:
app.master.title('Hello World')
# 主消息循环:
app.mainloop()

估计以后写GUI的机会可能很少,只会用到简单的,先暂时写这么多,如果有需要到时候在补充呗,你说对吧,科科~

猜你喜欢

转载自blog.csdn.net/alicelmx/article/details/80310184