python-简单GUI程序

2 案例2:简单GUI程序
2.1 问题
创建mygui.py脚本,要求如下:

窗口程序提供三个按钮
其中两个按钮的前景色均为白色,背景色为蓝色
第三个按钮前景色为红色,背景色为红色
按下第三个按钮后,程序退出
2.2 方案
1.导入tkinter模块、创建顶层窗口,顶层窗口只应该创建一次

2.添加窗口部件:用Label控件创建标签、用Butten控件来创建按钮

3.引入偏函数partial把tkinter.Button的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数重复创建按钮会更简单。对于有很多可调用对象,并且许多调用都反复使用相同参数的情况,使用偏函数比较合适。

4.创建第三个按钮需command绑定退出命令

5.最后将按钮及标签填充到界面

6.运行这个GUI应用

2.3 步骤
实现此案例需要按照如下步骤进行。

步骤一:编写脚本

[root@localhost day06]# vim mygui.py
#!/usr/bin/env python3
import tkinter
from functools import partial
root = tkinter.Tk()    #创建顶层窗口
lb1 = tkinter.Label(root, text="hello world!", font = "Aria 16 bold")#创建标签
b1 = tkinter.Button(root, bg='blue', fg='white', text="Button 1")#创建按钮
mybutton = partial(tkinter.Button, root, bg='blue', fg='white')
#调用新的函数时,给出改变的参数即可
b2 = mybutton(text='Button 2')
b3 = tkinter.Button(root, bg='red', fg='red', text='QUIT', command=root.quit)    #创建按钮,绑定了root.quit命令
lb1.pack()    #填充到界面
b1.pack()
b2.pack()
b3.pack()
root.mainloop()    #运行这个GUI应用

实现此案例还可用以下方法,需要注意的是:

Command绑定闭包函数返回函数块,上传多个参数调用闭包函数时,内层函数利用config方法替换标签内容

[root@localhost day06]# vim mygui.py
#!/usr/bin/env python3
import tkinter
from functools import partial
def say_hi(word):
    def welcome():
        lb1.config(text='hello %s!' % word)
    return welcome
root = tkinter.Tk()
lb1 = tkinter.Label(root, text="hello world!", font = "Aria 16 bold")
mybutton = partial(tkinter.Button, root, bg='blue', fg='white')
b1 = mybutton(text='Button 1', command=say_hi('aaa'))
b2 = mybutton(text='Button 2', command=say_hi('bbb'))
b3 = tkinter.Button(root, bg='red', fg='red', text='QUIT', command=root.quit)
lb1.pack()
b1.pack()
b2.pack()
b3.pack()
root.mainloop()

步骤二:测试脚本执行,结果如图-1、图-2、图-3所示:

[root@localhost day05]# python3  mygui.p

在这里插入图片描述

[root@localhost day06]# python3 mygui2.py
发布了46 篇原创文章 · 获赞 0 · 访问量 430

猜你喜欢

转载自blog.csdn.net/weixin_45942735/article/details/104134949