Python GUI 界面,三种布局方式、EXE打包(2)
Python GUI 界面,三种布局方式、EXE打包(2)
一、三种布局方式
pack () 流式布局,适合简单页面
从上往下 / 从左往右自动排列,适合简单界面
tk.Label(root,text="A").pack(side="left", padx=5)
tk.Label(root,text="B").pack(side="left", padx=5)
side="top"/"left"/"right"/"bottom"padx水平间距,pady垂直间距
grid () 网格布局,适合表单页面
按行、列摆放,类似表格,最常用
import tkinter as tk
root = tk.Tk()
root.title("grid网格布局")
tk.Label(root, text="姓名:").grid(row=0, column=0, padx=5,pady=5)
tk.Entry(root).grid(row=0, column=1, padx=5,pady=5)
tk.Label(root, text="年龄:").grid(row=1, column=0, padx=5,pady=5)
tk.Entry(root).grid(row=1, column=1, padx=5,pady=5)
root.mainloop()
row行号,column列号,从 0 开始。
place () 绝对坐标(x,y 像素定位)
精确指定位置,窗口缩放时控件不会跟着动,很少用。
tk.Label(root,text="测试").place(x=10,y=20)
不要混用 pack 和 grid 在同一个父窗口,会卡死!
二、常用控件清单
# 多行文本框 Text
text = tk.Text(root, width=40, height=5)
text.pack()
text.insert("end", "初始文字") # 插入文字
content = text.get("1.0", "end") # 获取全部内容
# 复选框 Checkbutton
var = tk.IntVar()
tk.Checkbutton(root, text="同意协议", variable=var).pack()
# 单选框 Radiobutton
radio_var = tk.StringVar()
tk.Radiobutton(root, text="选项A", variable=radio_var, value="A").pack()
tk.Radiobutton(root, text="选项B", variable=radio_var, value="B").pack()
# 消息弹窗
from tkinter import messagebox
messagebox.showinfo("提示", "信息弹窗")
messagebox.showerror("错误", "出错了")
三、打包成 exe(Windows 分发)
写完代码,别人电脑没有 Python 也能双击运行: 安装打包工具
pip install pyinstaller
打包命令
pyinstaller -w -F gui01.py
-F:打包成单个 exe 文件-w:运行时不弹出黑色控制台窗口(GUI 程序必须加) 打包完成后 exe 在dist文件夹内。
EXE打包方法:使用Python操作数据库 - Q&25 - 博客园
设计1:kinter 简易登录界面
import tkinter as tk
from tkinter import messagebox
# 创建主窗口
root = tk.Tk()
root.title("简易登录窗口") # 窗口标题
root.geometry("320x180") # 窗口大小 宽x高
# 定义登录按钮点击事件函数
def login_action():
# 获取输入框内容
username = entry_user.get().strip()
password = entry_pwd.get().strip()
# 简单校验逻辑
if username == "admin" and password == "123456":
messagebox.showinfo("成功", "登录成功!欢迎进入系统")
else:
messagebox.showerror("失败", "账号或密码错误!")
# 清空输入框函数
def clear_action():
entry_user.delete(0, tk.END)
entry_pwd.delete(0, tk.END)
# 界面控件布局
# 账号行
label_user = tk.Label(root, text="账号:")
label_user.place(x=60, y=40)
entry_user = tk.Entry(root, width=20)
entry_user.place(x=110, y=40)
# 密码行
label_pwd = tk.Label(root, text="密码:")
label_user.place(x=60, y=40)
entry_pwd = tk.Entry(root, width=20, show="*") # show="*" 密码隐藏
entry_pwd.place(x=110, y=80)
# 按钮
btn_login = tk.Button(root, text="登录", width=8, command=login_action)
btn_login.place(x=70, y=120)
btn_clear = tk.Button(root, text="清空", width=8, command=clear_action)
btn_clear.place(x=170, y=120)
# 主循环,窗口持续显示
root.mainloop()
遇到的问题,容易缩进错误,注意python是用缩进表示代码块
设计2:Tkinter 记事本,带掉电存储
电存储原理:程序退出时把文本内容写入本地 txt 文件,下次启动时自动读出来。这样关掉程序、甚至重启电脑,内容都不会丢。
import tkinter as tk
from tkinter import messagebox
import os
# 配置:保存文件的路径
# 记事本内容会存到这个文件里,跟本程序在同一个文件夹
SAVE_FILE = "我的记事本.txt"
# 功能函数
def load_notes():
"""程序启动时:如果保存文件存在,就把内容读出来显示到文本框"""
if os.path.exists(SAVE_FILE): # 判断文件是否存在
with open(SAVE_FILE, "r", encoding="utf-8") as f:
content = f.read()
text_widget.insert("1.0", content) # 从第1行第0列开始插入
def save_notes():
"""把文本框里的内容写入文件,实现数据掉电保存"""
# "1.0" 表示第1行第0列,tk.END 表示到文本末尾
content = text_widget.get("1.0", tk.END + "-1c") # -1c 去掉末尾自动多出来的换行
with open(SAVE_FILE, "w", encoding="utf-8") as f:
f.write(content)
status_label.config(text=f"已保存 √ 共{len(content)}字")
def on_closing():
"""点窗口右上角 X 关闭时,自动保存再退出"""
save_notes() # 先保存
root.destroy() # 再销毁窗口
# 创建主窗口
root = tk.Tk()
root.title("简易记事本 - 掉电自动保存")
root.geometry("600x450") # 宽x高
# 界面布局
# 顶部按钮栏,用一个 Frame 容器装两个按钮
btn_frame = tk.Frame(root)
btn_frame.pack(fill=tk.X, pady=5)
btn_save = tk.Button(btn_frame, text="手动保存", width=10, command=save_notes)
btn_save.pack(side=tk.LEFT, padx=20)
btn_clear = tk.Button(btn_frame, text="清空内容", width=10, command=lambda: text_widget.delete("1.0", tk.END))
btn_clear.pack(side=tk.LEFT, padx=10)
# 底部状态栏,
status_label = tk.Label(root, text="就绪", anchor=tk.W, bd=1, relief=tk.SUNKEN)
status_label.pack(fill=tk.X, side=tk.BOTTOM)
# 中间大文本编辑区,fill=BOTH + expand=True 让它随窗口缩放
text_widget = tk.Text(root, font=("微软雅黑", 12), wrap=tk.WORD) # wrap=WORD 按单词换行
text_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
# 启动时加载历史内容
load_notes()
# 绑定窗口关闭事件:点 X 时自动保存
root.protocol("WM_DELETE_WINDOW", on_closing)
# 主循环
root.mainloop()
| 代码 | 作用 |
|---|---|
open(SAVE_FILE, "w", encoding="utf-8") |
以写入模式打开文件,会覆盖旧内容 |
open(SAVE_FILE, "r", encoding="utf-8") |
以读取模式打开文件 |
f.write(content) |
把字符串写入文件 |
f.read() |
一次性读出全部内容 |
os.path.exists(路径) |
判断文件是否存在,避免第一次运行报错 |
root.protocol("WM_DELETE_WINDOW", on_closing) |
拦截窗口关闭动作,关闭前先执行保存 |
遇到的问题:
status_label 不显示,原因是 pack 布局顺序错误
tkinter 的 pack() 是按调用顺序渲染! 如果先 pack() 文本框 text_widget(fill=BOTH, expand=True),它会抢占所有剩余空间; 如果先 pack 状态栏,再 pack 文本框,状态栏才会出现在底部。
修正原则,先 pack 底部状态栏,再放中间文本框,原错误代码:

修正后:

设计3:带登录界面的音乐播放器
import tkinter as tk
from tkinter import ttk, messagebox, filedialog # 界面控件/弹窗/选文件夹对话框
import pygame # 音频播放引擎
import os # 判断文件/文件夹是否存在
import json # 掉电存储用的 JSON 读写
# ==================== 全局配置 ====================
CONFIG_FILE = "config.json" # 配置文件名,和本程序放同一目录
VALID_USER = "admin" # 登录预设账号
VALID_PWD = "123456" # 登录预设密码
MUSIC_EXTS = (".mp3", ".wav", ".ogg") # 只认这三种音乐格式
# 界面配色(浅灰背景 + 绿色主题,简约风)
BG_COLOR = "#f5f6fa" # 窗口背景色
FG_COLOR = "#2f3640" # 普通文字颜色
ACCENT = "#4cd137" # 列表选中高亮色(亮绿)
ACCENT_DARK = "#44bd32" # 当前歌曲文字色(深绿)
# ==================== JSON 读写工具(掉电存储核心) ====================
def load_config():
"""启动程序时读取 config.json,把上次的设置还原回来。
文件不存在或损坏时返回空字典,保证程序不报错。"""
if os.path.exists(CONFIG_FILE): # 先判断配置文件在不在
try:
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
return json.load(f) # 读出 JSON 并转成 Python 字典
except Exception:
return {} # 文件损坏就返回空,容错
return {}
def save_config(cfg):
"""关闭程序时把配置写回 config.json。
ensure_ascii=False 让中文正常显示,indent=2 让文件排版好看。"""
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(cfg, f, ensure_ascii=False, indent=2)
# ==================== 第一个窗口:登录 ====================
class LoginWindow:
def __init__(self, root):
# root 是传给本窗口的主窗口对象
self.root = root
self.root.title("音乐播放器 - 登录")
self.root.geometry("360x240") # 宽x高
self.root.resizable(False, False) # 禁止拖拽改变窗口大小
self.root.configure(bg=BG_COLOR) # 背景色
# ttk 是 tkinter 的现代化皮肤,统一设置各控件样式
style = ttk.Style()
style.configure("TLabel", background=BG_COLOR, foreground=FG_COLOR, font=("微软雅黑", 11))
style.configure("TEntry", font=("微软雅黑", 11))
style.configure("TButton", font=("微软雅黑", 11), padding=5)
# 大标题
ttk.Label(root, text="音乐播放器", font=("微软雅黑", 16, "bold")).pack(pady=(25, 15))
# 账号、密码输入区(用 frame 容器分组,grid 表格排列)
frame = ttk.Frame(root)
frame.pack(pady=5)
ttk.Label(frame, text="账号:").grid(row=0, column=0, padx=5, pady=8, sticky="e")
self.entry_user = ttk.Entry(frame, width=22)
self.entry_user.grid(row=0, column=1, padx=5, pady=8)
ttk.Label(frame, text="密码:").grid(row=1, column=0, padx=5, pady=8, sticky="e")
self.entry_pwd = ttk.Entry(frame, width=22, show="*") # show="*" 输入内容隐藏成圆点
self.entry_pwd.grid(row=1, column=1, padx=5, pady=8)
# 登录按钮,点击执行 check_login
ttk.Button(root, text="登 录", command=self.check_login).pack(pady=15, ipadx=30)
def check_login(self):
"""读取两个输入框内容,去空格后和预设账号密码比对。
对就关闭登录窗、打开播放器;错就弹窗提示。"""
u = self.entry_user.get().strip() # get() 取输入文字,strip() 去掉首尾空格
p = self.entry_pwd.get().strip()
if u == VALID_USER and p == VALID_PWD:
self.root.destroy() # 销毁登录窗口
open_player() # 调用函数打开播放器窗口
else:
messagebox.showerror("错误", "账号或密码错误")
# ==================== 第二个窗口:音乐播放器 ====================
class MusicPlayer:
def __init__(self, root):
self.root = root
self.root.title("简易音乐播放器")
self.root.geometry("500x450")
self.root.configure(bg=BG_COLOR)
# 读取上次保存的配置(掉电恢复)
self.cfg = load_config()
# ---------- 三个核心状态标志(理解播放器的关键) ----------
self.music_files = [] # 存每首歌的完整路径
self.current_idx = -1 # 当前选中/播放第几首,-1 表示还没选
self.is_playing = False # 是否"正在放声音",成功播起来才为 True
self.paused = False # 是否"暂停中"
pygame.mixer.init() # 初始化 pygame 音频引擎,必须在播之前调用
# ---------- 顶部:当前歌曲文字标签 ----------
self.now_playing = tk.Label(root, text="未播放",
bg=BG_COLOR, fg=ACCENT_DARK,
font=("微软雅黑", 12, "bold"))
self.now_playing.pack(pady=12)
# ---------- 中间:歌曲列表框 ----------
list_frame = tk.Frame(root, bg=BG_COLOR)
list_frame.pack(fill=tk.BOTH, expand=True, padx=20) # 占满剩余空间
# Listbox 列表框:展示所有歌曲名
self.listbox = tk.Listbox(list_frame, font=("微软雅黑", 10),
bg="#ffffff", fg=FG_COLOR,
selectbackground=ACCENT, selectforeground="white",
relief="flat", height=10)
self.listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# 右侧滚动条,和列表框联动
sb = ttk.Scrollbar(list_frame, command=self.listbox.yview)
sb.pack(side=tk.RIGHT, fill=tk.Y)
self.listbox.config(yscrollcommand=sb.set)
# 绑定双击事件:双击某一行就播放那首
self.listbox.bind("<Double-Button-1>", lambda e: self.play_selected())
# ---------- 中部:四个控制按钮 ----------
btn_frame = tk.Frame(root, bg=BG_COLOR)
btn_frame.pack(pady=12)
# grid 按一行四列摆放
self.btn_prev = ttk.Button(btn_frame, text="上一首", command=self.prev)
self.btn_prev.grid(row=0, column=0, padx=5)
self.btn_play = ttk.Button(btn_frame, text="播放", command=self.play_pause)
self.btn_play.grid(row=0, column=1, padx=5)
self.btn_stop = ttk.Button(btn_frame, text="停止", command=self.stop)
self.btn_stop.grid(row=0, column=2, padx=5)
self.btn_next = ttk.Button(btn_frame, text="下一首", command=self.next)
self.btn_next.grid(row=0, column=3, padx=5)
# ---------- 底部:打开文件夹 + 音量滑块 ----------
bottom = tk.Frame(root, bg=BG_COLOR)
bottom.pack(fill=tk.X, padx=20, pady=(0, 15))
ttk.Button(bottom, text="打开文件夹", command=self.choose_folder).pack(side=tk.LEFT)
tk.Label(bottom, text="音量", bg=BG_COLOR).pack(side=tk.LEFT, padx=(20, 2))
# Scale 滑块:0~100,拖动时实时调音量
self.volume = ttk.Scale(bottom, from_=0, to=100, command=self.set_volume, length=120)
self.volume.pack(side=tk.LEFT)
# ---------- 启动只恢复显示,绝不自动播放 ----------
self._restore_state()
# 启动自动切歌定时器:每 500ms 检查一次歌是否放完
self.root.after(500, self.check_music_end)
# 点窗口右上角 X 时,先执行 on_closing 保存配置再退出
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
# ---------- 掉电恢复:只加载列表、选中项、音量,不发声 ----------
def _restore_state(self):
folder = self.cfg.get("folder", "") # 上次的音乐文件夹
volume = self.cfg.get("volume", 70) # 上次音量,默认70
last_idx = self.cfg.get("last_index", -1) # 上次选中第几首
self.volume.set(volume)
self.set_volume(volume)
# 文件夹还存在才扫描,避免路径失效报错
if folder and os.path.isdir(folder):
self._scan_folder(folder)
# 把上次那首高亮选中、更新文字,但不调用播放
if 0 <= last_idx < len(self.music_files):
self.current_idx = last_idx
self.listbox.selection_set(last_idx)
self.now_playing.config(text=f"上次:{os.path.basename(self.music_files[last_idx])}")
# ---------- 选择音乐文件夹 ----------
def choose_folder(self):
folder = filedialog.askdirectory(title="选择音乐文件夹") # 弹出系统选目录框
if folder:
self._scan_folder(folder)
def _scan_folder(self, folder):
"""遍历文件夹,把音乐文件挑出来填进列表框"""
self.music_files.clear()
self.listbox.delete(0, tk.END) # 清空旧列表
self.current_idx = -1
# sorted 让歌曲按名字排序
for name in sorted(os.listdir(folder)):
if name.lower().endswith(MUSIC_EXTS): # 判断后缀是不是音乐格式
self.music_files.append(os.path.join(folder, name)) # 完整路径存列表
self.listbox.insert(tk.END, name) # 列表只显示文件名
self.cfg["folder"] = folder # 记住这个文件夹,下次自动用
if self.music_files:
self.now_playing.config(text=f"已加载 {len(self.music_files)} 首歌")
else:
messagebox.showinfo("提示", "该文件夹没有音乐文件")
# ---------- 播放控制 ----------
def play_selected(self):
"""双击列表项:拿到选中的序号后播放"""
sel = self.listbox.curselection() # 返回当前选中的元组
if sel:
self.current_idx = sel[0]
self.play_current()
def play_current(self):
"""真正加载并播放当前序号的歌;遇到损坏文件弹窗并自动跳过"""
if not self.music_files or self.current_idx < 0:
return
path = self.music_files[self.current_idx]
try:
pygame.mixer.music.load(path) # 把音乐文件载入内存
pygame.mixer.music.play() # 开始播放
# 成功播起来后,把状态标志置对
self.is_playing = True
self.paused = False
self.btn_play.config(text="暂停")
self.now_playing.config(text=os.path.basename(path)) # 顶部显示歌名
except pygame.error:
# 损坏/编码不兼容的 mp3 会走到这里,弹框并跳下一首,程序不崩
messagebox.showerror("文件错误", f"【{os.path.basename(path)}】损坏/编码不兼容,自动跳过")
self.next()
def play_pause(self):
"""播放键:根据当前状态在 播放/暂停/继续/停止后重播 之间切换"""
if self.current_idx < 0:
# 还没选歌,默认从第一首开始
if self.music_files:
self.current_idx = 0
self.listbox.selection_set(0)
self.play_current()
return
if self.paused:
# 状态1:暂停中 → 继续播放
pygame.mixer.music.unpause()
self.paused = False
self.is_playing = True
self.btn_play.config(text="暂停")
elif not pygame.mixer.music.get_busy():
# 状态2:停止状态(get_busy 返回 False)→ 重新播放当前歌,同时刷新顶部文字
self.play_current()
else:
# 状态3:正在播放 → 暂停
pygame.mixer.music.pause()
self.paused = True
self.is_playing = False # 暂停时退出"播放中",防止定时器误判为播完
self.btn_play.config(text="继续")
def stop(self):
"""停止:立刻停掉声音,回到待播放状态"""
pygame.mixer.music.stop()
self.is_playing = False
self.paused = False
self.btn_play.config(text="播放")
self.now_playing.config(text="已停止")
def prev(self):
"""上一首:取模循环,第一首的上一首自动跳到最后一首"""
if not self.music_files:
return
self.current_idx = (self.current_idx - 1) % len(self.music_files)
self.listbox.selection_clear(0, tk.END)
self.listbox.selection_set(self.current_idx)
self.play_current()
def next(self):
"""下一首:同样取模循环,最后一首的下一首回到第一首"""
if not self.music_files:
return
self.current_idx = (self.current_idx + 1) % len(self.music_files)
self.listbox.selection_clear(0, tk.END)
self.listbox.selection_set(self.current_idx)
self.play_current()
def set_volume(self, val):
"""音量滑块回调:pygame 音量范围是 0~1,所以除以100"""
pygame.mixer.music.set_volume(float(val) / 100)
# ---------- 自动切歌:只有"真的放完"才切 ----------
def check_music_end(self):
"""定时器每500ms跑一次。
必须同时满足:正在播放 且 没暂停 且 已不在发声(get_busy=False),
才认定为自然放完,自动切下一首。"""
if self.is_playing and not self.paused and not pygame.mixer.music.get_busy():
self.next()
# 再次安排下一次检查,形成循环定时
self.root.after(500, self.check_music_end)
# ---------- 关窗:保存配置(掉电存储写盘) ----------
def on_closing(self):
self.cfg["volume"] = int(float(self.volume.get())) # 存当前音量
self.cfg["last_index"] = self.current_idx # 存当前选中第几首
save_config(self.cfg) # 写入 config.json
pygame.mixer.music.stop() # 停止声音
self.root.destroy() # 关闭窗口
# ==================== 程序入口 ====================
def open_player():
"""登录成功后新建一个播放器主窗口并启动主循环"""
root2 = tk.Tk()
MusicPlayer(root2)
root2.mainloop()
# 直接运行本文件时,先弹登录窗口
if __name__ == "__main__":
root = tk.Tk()
LoginWindow(root)
root.mainloop()
浙公网安备 33010602011771号