当前位置: 移动技术网 > IT编程>脚本编程>Python > Python学习之旅(三十一)

Python学习之旅(三十一)

2018年12月13日  | 移动技术网IT编程  | 我要评论

女扮男装逍遥侯,dnf西西外挂,花魁的玩物txt

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()可以弹出消息对话框

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网