zoukankan      html  css  js  c++  java
  • 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()可以弹出消息对话框

  • 相关阅读:
    GCJ 2015-Qualification-A Standing Ovation 难度:0
    CF 103E Buying Sets 最大权闭合子图,匹配 难度:4
    HDU 1560 DNA sequence A* 难度:1
    蓝桥杯练习系统 矩阵翻硬币 大数,牛顿迭代法 难度:2
    Operating System Concepts with java 项目: Shell Unix 和历史特点
    HDU 2181 哈密顿绕行世界问题 dfs 难度:1
    HDU 3533 Escape bfs 难度:1
    HDU 3567 Eight II 打表,康托展开,bfs,g++提交可过c++不可过 难度:3
    POJ 1011 Sticks dfs,剪枝 难度:2
    UVALive 5905 Pool Construction 最小割,s-t割性质 难度:3
  • 原文地址:https://www.cnblogs.com/finsomway/p/10111672.html
Copyright © 2011-2022 走看看