设为首页 加入收藏

TOP

Python学习之旅(三十一)
2018-12-13 00:11:08 】 浏览:45
Tags:Python 学习 之旅 三十一

Python基础知识(30):图形界面(Ⅰ)

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

Tkinter可以满足基本的GUI程序的要求,此次以用Tkinter为例进行GUI编程

一、编写一个GUI版本的“Hello, world!”

本人使用的软件是pycharm

#导包
from tkinter import *

#从Frame派生一个Application类,这是所有Widget的父容器
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.qutiButton = Button(self, text='Quit', command=self.quit)
        self.qutiButton.pack()

#实例化Application,并启动消息循环
app = Application()
#设置窗口标题
app.master.title('Hello, world!')
#主消息循环
app.mainloop()

在GUI中,每个Button、Label、输入框等,都是一个Widget。

Frame则是可以容纳其他Widget的Widget,所有的Widget组合起来就是一棵树。

pack()方法把Widget加入到父容器中,并实现布局。pack()是最简单的布局,grid()可以实现更复杂的布局。

createWidgets()方法中,我们创建一个Label和一个Button,当Button被点击时,触发self.quit()使程序退出

点击“Quit”按钮或者窗口的“x”结束程序

二、添加文本输入

对这个GUI程序改进,加入一个文本框,让用户可以输入文本,然后点按钮后,弹出消息对话框

from tkinter import *
import tkinter.messagebox as messagebox

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'
        messagebox.showinfo('Message', 'Hello, %s' % name)

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

当用户点击按钮时,触发hello(),通过self.nameInput.get()获得用户输入的文本后,使用tkMessageBox.showinfo()可以弹出消息对话框

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇matplotlib简单示例 下一篇python装饰器的实现

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目