系列文章目录
Python 控件学习:购物菜单
文章目录
前言
这段代码是一个使用 Python 的 tkinter 库和 PIL(现在称为 Pillow)库实现的简单购物菜单程序。程序提供了一个图形用户界面(GUI),允许用户浏览商品、将商品添加到购物车、查看购物车内容、清空购物车以及查看购物车总额。
一、项目需求
要求程序允许用户浏览商品、将商品添加到购物车、查看购物车内容、清空购物车以及查看购物车总额,最后将购物车里面的信息保存到本地txt文件中,每次启动程序都可以调用上次保存的购物车。
二、库与商品的导入
1.引入库
代码如下(示例):
import tkinter as tk # 导入tkinter库,用于创建GUI
from tkinter import messagebox # 导入messagebox,用于显示弹出消息框
from PIL import Image, ImageTk # 导入PIL库中的Image和ImageTk模块,用于图像处理和显示
2.导入商品信息
代码如下(示例):
# 定义商品列表,每个商品有名称、价格和图片路径
products = {
'1': {'name': '苹果', 'price': 5.0, 'image_path': 'apple.png'},
'2': {'name': '香蕉', 'price': 3.0, 'image_path': 'banana.png'},
'3': {'name': '橙子', 'price': 4.0, 'image_path': 'orange.png'},
'4': {'name': '牛奶', 'price': 2.5, 'image_path': 'milk.png'},
'5': {'name': '葡萄', 'price': 6.0, 'image_path': 'grape.png'}
}
3.初始化字典
代码如下(示例):
# 初始化购物车字典,用于存储商品ID和对应的数量
cart = {}
三、购物车代码编写
1.文件保存函数
代码如下(示例):
# 保存购物车到文件的函数
def save_cart_to_file():
with open('cart.txt', 'w') as file: # 打开文件准备写入
for item, quantity in cart.items(): # 遍历购物车中的每个商品
file.write(f"{item}: {quantity}\n") # 将商品ID和数量写入文件
2.文件加载
代码如下(示例):
# 从文件加载购物车的函数
def load_cart_from_file():
global cart # 声明cart为全局变量
cart.clear() # 清空现有的购物车数据
try:
with open('cart.txt', 'r') as file: # 打开文件准备读取
for line in file:
item, quantity = line.strip().split(': ') # 分割每行数据
cart[item] = int(quantity) # 将数据存入购物车字典
except FileNotFoundError: # 如果文件不存在
pass # 忽略错误,购物车保持为空
show_cart() # 加载后显示购物车
3.清空购物车
代码如下(示例):
# 清空购物车的函数
def clear_cart():
global cart # 声明cart为全局变量
cart.clear() # 清空购物车
save_cart_to_file() # 保存空购物车到文件
show_cart() # 显示空购物车
4.总额计算
代码如下(示例):
# 计算购物车总额的函数
def calculate_total():
total = sum(products[str(item)]['price'] * quantity for item, quantity in cart.items()) # 计算总额
total_label.config(text=f"总额: {total:.2f}元") # 更新总额标签
5.购物车显示
代码如下(示例):
# 显示购物车的函数
def show_cart():
cart_list.delete(0, tk.END) # 清空购物车列表
calculate_total() # 计算并显示总额
for item, quantity in cart.items(): # 遍历购物车中的每个商品
product = products[item] # 获取商品详情
cart_list.insert(tk.END, f"{product['name']} - 数量: {quantity} - 单价: {product['price']}元") # 添加到购物车列表
6.商品添加
代码如下(示例):
# 添加商品到购物车的函数
def add_to_cart(product_id):
product_id = str(product_id) # 确保product_id是字符串
if product_id in cart:
cart[product_id] += 1 # 如果商品已存在,增加数量
else:
cart[product_id] = 1 # 否则,添加到购物车
save_cart_to_file() # 保存购物车到文件
show_cart() # 显示更新后的购物车
四、控件布局和调用
1.添加函数
代码如下(示例):
# 商品按钮命令的函数
def command_for_product(product_id):
return lambda: add_to_cart(product_id) # 返回一个lambda函数,用于添加商品到购物车
2.图片大小调整
代码如下(示例):
# 图片大小调整函数
def resize_image(image_path, size=(100, 100)):
try:
image = Image.open(image_path) # 打开图片文件
image = image.resize(size) # 调整图片大小
return ImageTk.PhotoImage(image) # 返回PIL图像的Tkinter兼容版本
except IOError:
messagebox.showerror("错误", f"图片文件 {image_path} 无法打开。") # 显示错误消息
return None
3.主窗口创建
代码如下(示例):
# 创建主窗口
root = tk.Tk()
root.title("购物菜单") # 设置窗口标题
4.商品区域布局
代码如下(示例):
# 商品展示区域
product_frame = tk.Frame(root)
product_frame.pack(side=tk.TOP, fill=tk.X, expand=True) # 将Frame添加到主窗口,并设置布局
5.商品横向排列
代码如下(示例):
# 横向排列商品
for key in sorted(products.keys()):
product = products[key]
photo = resize_image(product['image_path']) # 调整图片大小
if photo: # 如果图片加载成功
button = tk.Button(product_frame, image=photo, command=command_for_product(key)) # 创建商品按钮
button.image = photo # 保持对图片的引用
button.pack(side=tk.LEFT, padx=(10, 0), pady=10) # 将按钮添加到Frame,设置布局和边距
6.购物车布局与总额显示
代码如下(示例):
# 购物车显示区域
cart_list = tk.Listbox(root)
cart_list.pack(side=tk.TOP, fill=tk.BOTH, expand=True) # 将Listbox添加到主窗口,并设置布局
# 购物车总额显示
total_label = tk.Label(root, text="总额: 0.00元")
total_label.pack(side=tk.TOP, fill=tk.X) # 将Label添加到主窗口,并设置布局
7.购物车清空
代码如下(示例):
# 清空购物车按钮
clear_cart_button = tk.Button(root, text="清空购物车", command=clear_cart)
clear_cart_button.pack(side=tk.TOP, fill=tk.X) # 将按钮添加到主窗口,并设置布局
8.加载与运行
代码如下(示例):
# 加载购物车
load_cart_from_file() # 程序启动时加载购物车
# 运行主循环
root.mainloop() # 进入tkinter的事件循环,等待用户操作
五、源码与效果展示
1.源代码
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk
# 定义商品列表
products = {
'1': {'name': '苹果', 'price': 5.0, 'image_path': 'apple.png'},
'2': {'name': '香蕉', 'price': 3.0, 'image_path': 'banana.png'},
'3': {'name': '橙子', 'price': 4.0, 'image_path': 'orange.png'},
'4': {'name': '牛奶', 'price': 2.5, 'image_path': 'milk.png'},
'5': {'name': '葡萄', 'price': 6.0, 'image_path': 'grape.png'}
}
# 购物车字典
cart = {}
# 保存购物车到文件
def save_cart_to_file():
with open('cart.txt', 'w') as file:
for item, quantity in cart.items():
file.write(f"{item}: {quantity}\n")
# 从文件加载购物车
def load_cart_from_file():
global cart
cart.clear()
try:
with open('cart.txt', 'r') as file:
for line in file:
item, quantity = line.strip().split(': ')
cart[item] = int(quantity)
except FileNotFoundError:
pass
show_cart()
# 清空购物车
def clear_cart():
global cart
cart.clear()
save_cart_to_file()
show_cart()
# 计算购物车总额
def calculate_total():
total = sum(products[str(item)]['price'] * quantity for item, quantity in cart.items())
total_label.config(text=f"总额: {total:.2f}元")
# 显示购物车
def show_cart():
cart_list.delete(0, tk.END)
calculate_total()
for item, quantity in cart.items():
product = products[item]
cart_list.insert(tk.END, f"{product['name']} - 数量: {quantity} - 单价: {product['price']}元")
# 添加商品到购物车
def add_to_cart(product_id):
product_id = str(product_id) # 确保 product_id 是字符串类型
if product_id in cart:
cart[product_id] += 1
else:
cart[product_id] = 1
save_cart_to_file()
show_cart()
# 商品按钮命令
def command_for_product(product_id):
return lambda: add_to_cart(product_id)
# 图片大小调整函数
def resize_image(image_path, size=(100, 100)):
try:
image = Image.open(image_path)
image = image.resize(size)
return ImageTk.PhotoImage(image)
except IOError:
messagebox.showerror("错误", f"图片文件 {image_path} 无法打开。")
return None
# 创建主窗口
root = tk.Tk()
root.title("购物菜单")
# 商品展示区域
product_frame = tk.Frame(root)
product_frame.pack(side=tk.TOP, fill=tk.X, expand=True)
# 横向排列商品
for key in sorted(products.keys()):
product = products[key]
photo = resize_image(product['image_path']) # 调整图片大小
if photo: # 如果图片加载成功
button = tk.Button(product_frame, image=photo, command=command_for_product(key))
button.image = photo # Keep a reference!
button.pack(side=tk.LEFT, padx=(10, 0), pady=10) # 水平排列商品
# 购物车显示区域
cart_list = tk.Listbox(root)
cart_list.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# 购物车总额显示
total_label = tk.Label(root, text="总额: 0.00元")
total_label.pack(side=tk.TOP, fill=tk.X)
# 清空购物车按钮
clear_cart_button = tk.Button(root, text="清空购物车", command=clear_cart)
clear_cart_button.pack(side=tk.TOP, fill=tk.X)
# 加载购物车
load_cart_from_file()
# 运行主循环
root.mainloop()
2.效果展示
总结
以上代码展示了一个简单的图形界面应用程序,用户可以通过它添加商品到购物车,查看购物车内容,并进行清空操作。程序使用了 tkinter 库来创建GUI,以及 Pillow 库来处理和显示图片。程序的核心功能包括商品展示、购物车管理、总额计算和显示,以及文件读写操作以保存和加载购物车状态。如果你觉得不错,请给我一个赞与关注吧OvO!