• python 图形界面


    Python自带的库是支持Tk的Tkinter,使用Tkinter,无需安装任何包,就可以直接使用。

    Tk是一个图形库,支持多个操作系统

    导入Tkinter包的所有内容:

    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.quitButton = Button(self, text='Quit', command=self.quit)
            self.quitButton.pack()

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


    pack()方法把Widget加入到父容器中,并实现布局。
    在createWidgets()方法中,创建一个Label和一个Button,当Button被点击时,触发self.quit()使程序退出。


    实例化Application,并启动消息循环:

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


    GUI程序的主线程负责监听来自操作系统的消息,并依次处理每一条消息


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

    朝闻道
  • 相关阅读:
    CSS中expression使用简介
    过滤Html标签代码
    ASP.NET上传图片时显示预览
    30分钟搞定.net正则表达式
    DataFormatString格式化
    Js事件大全
    Hibernate关联映射
    动态给下拉框添加选项
    python模块整理文章导航
    python学习笔记文章导航
  • 原文地址:https://www.cnblogs.com/wander-clouds/p/8513259.html
Copyright © 2020-2023  润新知