1 目的
- 了解Python GUI编程;
- 熟悉GUI编程的大致流程;
- 熟悉组件和用户行为交互的方式。
2 GUI编码流程
基本上使用tkinter来开发GUI应用需要以下5个步骤:
- 导入tkinter模块中我们需要的东西。(导包)
- 创建一个顶层窗口对象并用它来承载整个GUI应用。
- 在顶层窗口对象上添加GUI组件。
- 通过代码将这些GUI组件的功能组织起来。
- 进入主事件循环(main loop)。
3 牛刀小试——修改label的内容和颜色
***注意confirm_to_quit中需要最后加入“ exit(0)”退出程序的时候才不会卡死!***
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2021/6/24 17:38
# @Author : Yujie_Xue
# @Email : xyj19970628@163.com
# @File : 10.1 gui应用(tkinter).py
# @Software: PyCharm 2019.1
"""
基本上使用tkinter来开发GUI应用需要以下5个步骤:
1. 导入tkinter模块中我们需要的东西。(导包)
2. 创建一个顶层窗口对象并用它来承载整个GUI应用。
3. 在顶层窗口对象上添加GUI组件。
4. 通过代码将这些GUI组件的功能组织起来。
5. 进入主事件循环(main loop)。
"""
import tkinter
import tkinter.messagebox
def main():
flag = True
# 修改标签上的文字
def change_label_text():
# 触发这个事件可以重新配置标签的颜色
nonlocal flag
flag = not flag
color, msg = ('red', 'Hello, world!') \
if flag else ('blue', 'Goodbye, world!')
label.config(text=msg, fg=color)
# 这个标签一定有这两个属性
# 确认退出
def confirm_to_quit():
if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'):
top.quit() # 退出!
exit(0) # 加一个这个就不会卡死了!!!
# 创建顶层窗口
top = tkinter.Tk()
# 设置窗口大小
top.geometry('240x160')
# 设置窗口标题
top.title('小游戏')
# 创建标签对象并添加到顶层窗口
label = tkinter.Label(top, text='Hello world!', font='Arial-32', fg='red')
label.pack(expand=1)
# 创建一个装按钮的容器
panel = tkinter.Frame(top)
# 创建按钮对象 指定添加到哪个容器中,通过command参数绑定时间回调函数
button1 = tkinter.Button(panel, text='修改', command = change_label_text)
button1.pack(side='left')
button2 = tkinter.Button(panel, text='退出', command = confirm_to_quit)
button2.pack(side='right')
panel.pack(side='bottom')
# 开启主事件循环
tkinter.mainloop() # 为什么会卡死?
if __name__ == '__main__':
main()
4 运行效果
点一下修改:
点一下退出:
确定后即可退出程序。