second commit

main
123 6 months ago
parent 2a26acec8a
commit cf497d87cf

@ -1,182 +1,107 @@
import tkinter as tk import tkinter as tk
from tkinter import ttk, messagebox
import pymysql import pymysql
from tkinter import messagebox
class JiaJuPage: class JiaJuPage:
def __init__(self, master): def __init__(self, master):
self.root = master self.root = master
self.page = tk.Frame(self.root) self.root.title("智能家居系统 - 家居管理")
self.page.pack() self.root.geometry('1000x700')
self.root.geometry('600x400')
self.create_page()
def create_page(self):
menubar = tk.Menu(self.root)
# 数据库连接配置
self.conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统', self.conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统',
charset='utf8mb4') charset='utf8mb4')
self.cursor = self.conn.cursor() self.cursor = self.conn.cursor()
menubar.add_command(label='录入家居', command=self.add_jiaju) self.create_widgets()
menubar.add_command(label='查询家居', command=self.query_jiaju)
menubar.add_command(label='删除家居', command=self.delete_jiaju) def create_widgets(self):
menubar.add_command(label='修改家居', command=self.update_jiaju) # 创建表格框架和滚动条
menubar.add_separator() # 添加分隔线使菜单更加清晰 frame = tk.Frame(self.root)
menubar.add_command(label='退出', command=self.exit_app) # 新增退出功能 frame.pack(fill=tk.BOTH, expand=True)
self.root.config(menu=menubar) scrollbar_y = tk.Scrollbar(frame, orient=tk.VERTICAL)
scrollbar_x = tk.Scrollbar(frame, orient=tk.HORIZONTAL)
def exit_app(self):
"""退出应用程序的函数""" self.tree = ttk.Treeview(frame, columns=("ID", "名称", "颜色", "品牌", "价格", "生产日期"),
if messagebox.askyesno("退出确认", "确定要退出吗?"): yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
self.close_conn() # 确保关闭数据库连接 self.tree.heading("#0", text="")
self.root.destroy() # 关闭主窗口 self.tree.heading("ID", text="ID")
self.tree.heading("名称", text="名称")
def add_jiaju(self): self.tree.heading("颜色", text="颜色")
def submit(): self.tree.heading("品牌", text="品牌")
# 获取用户输入 self.tree.heading("价格", text="价格")
name = entry_name.get() self.tree.heading("生产日期", text="生产日期")
color = entry_color.get() self.tree.column("#0", width=0, stretch=tk.NO)
brand = entry_brand.get() self.tree.column("ID", anchor=tk.CENTER, width=50)
price = entry_price.get() self.tree.column("名称", anchor=tk.CENTER, width=100)
production_date = entry_production_date.get() self.tree.column("颜色", anchor=tk.CENTER, width=100)
# 插入数据库操作 self.tree.column("品牌", anchor=tk.CENTER, width=100)
sql = f"INSERT INTO jia_ju(name, color, brand, price, production_date) VALUES ('{name}', '{color}', '{brand}', {price}, '{production_date}')" self.tree.column("价格", anchor=tk.CENTER, width=100)
try: self.tree.column("生产日期", anchor=tk.CENTER, width=100)
self.cursor.execute(sql)
self.conn.commit() self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
messagebox.showinfo("成功", "家居信息录入成功!") scrollbar_y.config(command=self.tree.yview)
except Exception as e: scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
messagebox.showerror("错误", f"录入失败: {e}") scrollbar_x.config(command=self.tree.xview)
finally: scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
add_window.destroy() # 关闭对话框
# 按钮区域
add_window = tk.Toplevel(self.root) button_frame = tk.Frame(self.root)
add_window.title("录入家居信息") button_frame.pack(pady=10)
tk.Label(add_window, text="名称:").pack()
entry_name = tk.Entry(add_window) tk.Button(button_frame, text="添加家居", command=self.add_jiaju_popup).pack(side=tk.LEFT, padx=10)
entry_name.pack() tk.Button(button_frame, text="删除选中", command=self.delete_selected_jiaju).pack(side=tk.LEFT, padx=10)
tk.Label(add_window, text="颜色:").pack() tk.Button(button_frame, text="修改选中", command=self.update_selected_jiaju_popup).pack(side=tk.LEFT, padx=10)
entry_color = tk.Entry(add_window) tk.Button(button_frame, text="查询所有", command=self.query_all_jiaju).pack(side=tk.LEFT, padx=10)
entry_color.pack() tk.Button(button_frame, text="返回主页面", command=self.query_all_jiaju).pack(side=tk.LEFT, padx=10)
tk.Label(add_window, text="品牌:").pack()
entry_brand = tk.Entry(add_window) query_frame = tk.Frame(self.root)
entry_brand.pack() query_frame.pack(pady=(10, 0)) # 添加一些垂直间隔
tk.Label(add_window, text="价格:").pack()
entry_price = tk.Entry(add_window) tk.Label(query_frame, text="名称:").pack(side=tk.LEFT)
entry_price.pack() self.entry_name_query = tk.Entry(query_frame)
tk.Label(add_window, text="生产日期:").pack() self.entry_name_query.pack(side=tk.LEFT, padx=(5, 0)) # 为输入框之间添加一点水平间隔
entry_production_date = tk.Entry(add_window)
entry_production_date.pack() tk.Label(query_frame, text="颜色:").pack(side=tk.LEFT)
tk.Button(add_window, text="提交", command=submit).pack() self.entry_color_query = tk.Entry(query_frame)
self.entry_color_query.pack(side=tk.LEFT, padx=(5, 0))
def query_jiaju(self):
tk.Label(query_frame, text="品牌:").pack(side=tk.LEFT)
self.entry_brand_query = tk.Entry(query_frame)
self.entry_brand_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="价格:").pack(side=tk.LEFT)
self.entry_price_query = tk.Entry(query_frame)
self.entry_price_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="生产日期:").pack(side=tk.LEFT)
self.entry_production_date_query = tk.Entry(query_frame)
self.entry_production_date_query.pack(side=tk.LEFT)
tk.Button(query_frame, text="查询", command=self.query_jiaju_condition).pack(side=tk.LEFT, padx=10)
self.query_all_jiaju() # 初始化加载所有数据
def query_all_jiaju(self):
self.tree.delete(*self.tree.get_children())
self.cursor.execute("SELECT * FROM jia_ju") self.cursor.execute("SELECT * FROM jia_ju")
results = self.cursor.fetchall() rows = self.cursor.fetchall()
if results: for row in rows:
result_text = "\n".join([str(row) for row in results]) self.tree.insert('', tk.END, values=row)
messagebox.showinfo("查询结果", result_text)
else:
messagebox.showinfo("查询结果", "无数据")
def delete_jiaju(self):
def confirm_delete():
item_id = entry_id.get()
# 执行删除操作
sql = f"DELETE FROM jia_ju WHERE id={item_id}"
try:
self.cursor.execute(sql)
self.conn.commit()
messagebox.showinfo("成功", "家居信息已删除!")
except Exception as e:
messagebox.showerror("错误", f"删除失败: {e}")
finally:
delete_window.destroy()
delete_window = tk.Toplevel(self.root)
delete_window.title("删除家居")
tk.Label(delete_window, text="请输入家居ID:").pack()
entry_id = tk.Entry(delete_window)
entry_id.pack()
tk.Button(delete_window, text="确认删除", command=confirm_delete).pack()
def update_jiaju(self):
def fetch_jiaju_info():
item_id = entry_id.get()
sql = f"SELECT * FROM jia_ju WHERE id={item_id}"
try:
self.cursor.execute(sql)
result = self.cursor.fetchone()
if result:
entry_name.delete(0, tk.END)
entry_name.insert(tk.END, result[1])
entry_color.delete(0, tk.END)
entry_color.insert(tk.END, result[2])
entry_brand.delete(0, tk.END)
entry_brand.insert(tk.END, result[3])
entry_price.delete(0, tk.END)
entry_price.insert(tk.END, str(result[4]))
entry_production_date.delete(0, tk.END)
entry_production_date.insert(tk.END, result[5])
else:
messagebox.showinfo("查询结果", "未找到该家居信息")
except Exception as e:
messagebox.showerror("错误", f"查询失败: {e}")
def submit_update():
item_id = entry_id.get()
name = entry_name.get()
color = entry_color.get()
brand = entry_brand.get()
price = entry_price.get()
production_date = entry_production_date.get()
sql = f"UPDATE jia_ju SET name='{name}', color='{color}', brand='{brand}', price={price}, production_date='{production_date}' WHERE id={item_id}"
try:
self.cursor.execute(sql)
self.conn.commit()
messagebox.showinfo("成功", "家居信息已更新!")
except Exception as e:
messagebox.showerror("错误", f"更新失败: {e}")
finally:
update_window.destroy()
update_window = tk.Toplevel(self.root)
update_window.title("修改家居信息")
tk.Label(update_window, text="请输入家居ID:").pack()
entry_id = tk.Entry(update_window)
entry_id.pack()
tk.Button(update_window, text="查询", command=fetch_jiaju_info).pack()
tk.Label(update_window, text="名称:").pack()
entry_name = tk.Entry(update_window)
entry_name.pack()
tk.Label(update_window, text="颜色:").pack()
entry_color = tk.Entry(update_window)
entry_color.pack()
tk.Label(update_window, text="品牌:").pack()
entry_brand = tk.Entry(update_window)
entry_brand.pack()
tk.Label(update_window, text="价格:").pack()
entry_price = tk.Entry(update_window)
entry_price.pack()
tk.Label(update_window, text="生产日期:").pack()
entry_production_date = tk.Entry(update_window)
entry_production_date.pack()
tk.Button(update_window, text="提交修改", command=submit_update).pack()
def close_conn(self): def close_conn(self):
# 关闭数据库连接
self.cursor.close() self.cursor.close()
self.conn.close() self.conn.close()
self.root.destroy()
if __name__ == '__main__': if __name__ == '__main__':
root = tk.Tk() root = tk.Tk()
app = JiaJuPage(root) app = JiaJuPage(root)
# 确保在程序结束时关闭数据库连接
root.protocol("WM_DELETE_WINDOW", app.close_conn) root.protocol("WM_DELETE_WINDOW", app.close_conn)
root.mainloop() root.mainloop()

@ -1,7 +1,224 @@
from 测试 import db, Jia import tkinter as tk
from tkinter import ttk, messagebox
import pymysql
s1 = Jia(编号=1, 名称='电脑', 品牌='联想', 颜色='黑色', 价格='5000', 生产日期='2020-01-01')
s2 = Jia(编号=2, 名称='冰箱', 品牌='联想', 颜色='白色', 价格='6000', 生产日期='2020-01-02') class JiaJuPage:
s3 = Jia(编号=2, 名称='电视机', 品牌='联想', 颜色='黑色', 价格='3000', 生产日期='2020-01-02') def __init__(self, master):
db.session.add(s) self.root = master
db.session.commit() self.root.title("智能家居系统 - 家居管理")
self.root.geometry('800x700')
self.conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统',
charset='utf8mb4')
self.cursor = self.conn.cursor()
self.create_widgets()
def create_widgets(self):
# 创建表格框架和滚动条
frame = tk.Frame(self.root)
frame.pack(fill=tk.BOTH, expand=True)
scrollbar_y = tk.Scrollbar(frame, orient=tk.VERTICAL)
scrollbar_x = tk.Scrollbar(frame, orient=tk.HORIZONTAL)
self.tree = ttk.Treeview(frame, columns=("ID", "名称", "颜色", "品牌", "价格", "生产日期"),
yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
self.tree.heading("#0", text="")
self.tree.heading("ID", text="ID")
self.tree.heading("名称", text="名称")
self.tree.heading("颜色", text="颜色")
self.tree.heading("品牌", text="品牌")
self.tree.heading("价格", text="价格")
self.tree.heading("生产日期", text="生产日期")
self.tree.column("#0", width=0, stretch=tk.NO)
self.tree.column("ID", anchor=tk.CENTER, width=50)
self.tree.column("名称", anchor=tk.CENTER, width=100)
self.tree.column("颜色", anchor=tk.CENTER, width=100)
self.tree.column("品牌", anchor=tk.CENTER, width=100)
self.tree.column("价格", anchor=tk.CENTER, width=100)
self.tree.column("生产日期", anchor=tk.CENTER, width=100)
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar_y.config(command=self.tree.yview)
scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
scrollbar_x.config(command=self.tree.xview)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
# 按钮区域
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10)
tk.Button(button_frame, text="添加家居", command=self.add_jiaju_popup).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="删除选中", command=self.delete_selected_jiaju).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="修改选中", command=self.update_selected_jiaju_popup).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="查询所有", command=self.query_all_jiaju).pack(side=tk.LEFT, padx=10)
self.query_all_jiaju() # 初始化加载所有数据
def query_all_jiaju(self):
self.tree.delete(*self.tree.get_children())
self.cursor.execute("SELECT * FROM jia_ju")
rows = self.cursor.fetchall()
for row in rows:
self.tree.insert('', tk.END, values=row)
def add_jiaju_popup(self):
def submit_add():
name = entry_name.get()
color = entry_color.get()
brand = entry_brand.get()
price = entry_price.get()
production_date = entry_production_date.get()
sql = f"INSERT INTO jia_ju(name, color, brand, price, production_date) VALUES ('{name}', '{color}', '{brand}', {price}, '{production_date}')"
try:
self.cursor.execute(sql)
self.conn.commit()
messagebox.showinfo("成功", "家居信息录入成功!")
add_window.destroy() # 关闭弹窗后刷新列表
self.query_all_jiaju()
except Exception as e:
messagebox.showerror("错误", f"录入失败: {e}")
add_window = tk.Toplevel(self.root)
add_window.title("录入家居信息")
tk.Label(add_window, text="名称:").pack()
entry_name = tk.Entry(add_window)
entry_name.pack()
tk.Label(add_window, text="颜色:").pack()
entry_color = tk.Entry(add_window)
entry_color.pack()
tk.Label(add_window, text="品牌:").pack()
entry_brand = tk.Entry(add_window)
entry_brand.pack()
tk.Label(add_window, text="价格:").pack()
entry_price = tk.Entry(add_window)
entry_price.pack()
tk.Label(add_window, text="生产日期:").pack()
entry_production_date = tk.Entry(add_window)
entry_production_date.pack()
tk.Button(add_window, text="提交", command=submit_add).pack()
def delete_selected_jiaju(self):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请先选择要删除的家居项!")
return
for item in selected_items:
item_id = self.tree.item(item)['values'][0]
sql = f"DELETE FROM jia_ju WHERE id={item_id}"
try:
self.cursor.execute(sql)
self.conn.commit()
except Exception as e:
messagebox.showerror("错误", f"删除失败: {e}")
self.conn.rollback()
return
messagebox.showinfo("成功", "选中的家居信息已删除!")
self.query_all_jiaju() # 刷新列表
def update_selected_jiaju_popup(self):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请先选择要修改的家居项!")
return
item = selected_items[0] # 假设一次只修改一项
item_values = self.tree.item(item)['values']
item_id = item_values[0]
def submit_update():
name = entry_name.get()
color = entry_color.get()
brand = entry_brand.get()
price = entry_price.get()
production_date = entry_production_date.get()
sql = f"UPDATE jia_ju SET name='{name}', color='{color}', brand='{brand}', price={price}, production_date='{production_date}' WHERE id={item_id}"
try:
self.cursor.execute(sql)
self.conn.commit()
messagebox.showinfo("成功", "家居信息已更新!")
update_window.destroy() # 关闭弹窗后刷新列表
self.query_all_jiaju()
except Exception as e:
messagebox.showerror("错误", f"更新失败: {e}")
update_window = tk.Toplevel(self.root)
update_window.title("修改家居信息")
tk.Label(update_window, text="名称:").pack()
entry_name = tk.Entry(update_window)
entry_name.insert(tk.END, item_values[1]) # 预填充现有值
entry_name.pack()
tk.Label(update_window, text="颜色:").pack()
entry_color = tk.Entry(update_window)
entry_color.insert(tk.END, item_values[2])
entry_color.pack()
tk.Label(update_window, text="品牌:").pack()
entry_brand = tk.Entry(update_window)
entry_brand.insert(tk.END, item_values[3])
entry_brand.pack()
tk.Label(update_window, text="价格:").pack()
entry_price = tk.Entry(update_window)
entry_price.insert(tk.END, item_values[4])
entry_price.pack()
tk.Label(update_window, text="生产日期:").pack()
entry_production_date = tk.Entry(update_window)
entry_production_date.insert(tk.END, item_values[5])
entry_production_date.pack()
tk.Button(update_window, text="提交修改", command=submit_update).pack()
def close_conn(self):import tkinter as tk
from tkinter import messagebox
from 家居信息 import JiaJuPage
class MainPage:
def __init__(self, master):
self.root = master
self.page = tk.Frame(self.root)
self.page.pack()
self.root.geometry('600x400')
self.create_page()
def create_page(self):
# 创建一个标签用于展示简单的家居信息标题
self.home_info_title = tk.Label(self.page, text="主页面区", font=("Helvetica", 16))
self.home_info_title.pack(pady=20)
# 添加一个按钮用于跳转到家居信息页面
self.goto_jiaju_button = tk.Button(self.page, text="家居信息", command=self.show_jiaju_info)
self.goto_jiaju_button.pack(pady=10)
def show_jiaju_info(self):
# 销毁当前页面
self.page.destroy()
# 显示家居信息页面
JiaJuInfoPage(self.root)
class JiaJuInfoPage:
def __init__(self, master):
self.root = master
self.page = tk.Frame(self.root)
self.page.pack()
self.root.geometry('600x400')
JiaJuPage(self.root)
if __name__ == '__main__':
root = tk.Tk()
app = MainPage(root)
root.mainloop()
self.cursor.close()
self.conn.close()
self.root.destroy()
if __name__ == '__main__':
root = tk.Tk()
app = JiaJuPage(root)
root.protocol("WM_DELETE_WINDOW", app.close_conn)
root.mainloop()

@ -1,5 +1,6 @@
import tkinter as tk import tkinter as tk
from tkinter import messagebox from tkinter import messagebox
from 家居信息 import JiaJuPage
class MainPage: class MainPage:
def __init__(self, master): def __init__(self, master):
@ -8,17 +9,25 @@ class MainPage:
self.page.pack() self.page.pack()
self.root.geometry('600x400') self.root.geometry('600x400')
self.create_page() self.create_page()
def create_page(self): def create_page(self):
# 创建一个标签用于展示简单的家居信息标题 # 创建一个标签用于展示简单的家居信息标题
self.home_info_title = tk.Label(self.page, text="主页面区", font=("Helvetica", 16)) self.home_info_title = tk.Label(self.page, text="主页面区", font=("Helvetica", 16))
self.home_info_title.pack(pady=20) self.home_info_title.pack(pady=20)
# 添加一个按钮用于跳转到家居信息页面
# 创建一个按钮,点击后显示更详细的家居信息 self.goto_jiaju_button = tk.Button(self.page, text="家居信息", command=self.show_jiaju_info)
self.view_details_button = tk.Button(self.page, text="家居信息", command=self.view_home_details) self.goto_jiaju_button.pack(pady=10)
self.view_details_button.pack(pady=10) def show_jiaju_info(self):
# 销毁当前页面
self.page.destroy()
# 显示家居信息页面
JiaJuInfoPage(self.root)
class JiaJuInfoPage:
def __init__(self, master):
self.root = master
self.page = tk.Frame(self.root)
self.page.pack()
self.root.geometry('600x400')
JiaJuPage(self.root)
if __name__ == '__main__': if __name__ == '__main__':
root = tk.Tk() root = tk.Tk()

@ -1,32 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>家居管理</title>
<script>
function openWindow(message) {
var win = window.open("", "家居操作结果", "width=400,height=200");
win.document.write("<p>" + message + "</p>");
}
</script>
</head>
<body>
<!-- 你的表单或其他交互元素 -->
<form id="jiaju-form">
<!-- 表单字段... -->
<button type="submit" onclick="sendRequest()">提交</button>
</form>
<script>
function sendRequest() {
// 发送AJAX请求到后端
fetch('/add_jiaju', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ /* 你的JSON数据 */ })
}).then(response => response.json())
.then(data => openWindow(data.message))
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>

@ -1,57 +1,111 @@
import tkinter as tk import tkinter as tk
from tkinter import ttk, messagebox
import pymysql import pymysql
from tkinter import messagebox #from 主页面 import MainPage
class JiaJuPage: class JiaJuPage:
def __init__(self, master): def __init__(self, master):
self.root = master self.root = master
self.page = tk.Frame(self.root) self.root.title("智能家居系统 - 家居管理")
self.page.pack() self.root.geometry('1000x700')
self.root.geometry('600x400')
self.create_page()
def create_page(self):
menubar = tk.Menu(self.root)
# 数据库连接配置
self.conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统', self.conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统',
charset='utf8mb4') charset='utf8mb4')
self.cursor = self.conn.cursor() self.cursor = self.conn.cursor()
menubar.add_command(label='录入家居', command=self.add_jiaju) self.create_widgets()
menubar.add_command(label='查询家居', command=self.query_jiaju)
menubar.add_command(label='删除家居', command=self.delete_jiaju) def create_widgets(self):
menubar.add_command(label='修改家居', command=self.update_jiaju) # 创建表格框架和滚动条
menubar.add_separator() # 添加分隔线使菜单更加清晰 frame = tk.Frame(self.root)
menubar.add_command(label='退出', command=self.exit_app) # 新增退出功能 frame.pack(fill=tk.BOTH, expand=True)
self.root.config(menu=menubar) scrollbar_y = tk.Scrollbar(frame, orient=tk.VERTICAL)
scrollbar_x = tk.Scrollbar(frame, orient=tk.HORIZONTAL)
def exit_app(self):
"""退出应用程序的函数""" self.tree = ttk.Treeview(frame, columns=("ID", "名称", "颜色", "品牌", "价格", "生产日期"),
if messagebox.askyesno("退出确认", "确定要退出吗?"): yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
self.close_conn() # 确保关闭数据库连接 self.tree.heading("#0", text="")
self.root.destroy() # 关闭主窗口 self.tree.heading("ID", text="ID")
self.tree.heading("名称", text="名称")
self.tree.heading("颜色", text="颜色")
self.tree.heading("品牌", text="品牌")
self.tree.heading("价格", text="价格")
self.tree.heading("生产日期", text="生产日期")
self.tree.column("#0", width=0, stretch=tk.NO)
self.tree.column("ID", anchor=tk.CENTER, width=50)
self.tree.column("名称", anchor=tk.CENTER, width=100)
self.tree.column("颜色", anchor=tk.CENTER, width=100)
self.tree.column("品牌", anchor=tk.CENTER, width=100)
self.tree.column("价格", anchor=tk.CENTER, width=100)
self.tree.column("生产日期", anchor=tk.CENTER, width=100)
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar_y.config(command=self.tree.yview)
scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
scrollbar_x.config(command=self.tree.xview)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
# 按钮区域
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10)
tk.Button(button_frame, text="添加家居", command=self.add_jiaju_popup).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="删除选中", command=self.delete_selected_jiaju).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="修改选中", command=self.update_selected_jiaju_popup).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="查询所有", command=self.query_all_jiaju).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="返回主页面", command=self.query_all_jiaju).pack(side=tk.LEFT, padx=10)
query_frame = tk.Frame(self.root)
query_frame.pack(pady=(10, 0)) # 添加一些垂直间隔
tk.Label(query_frame, text="名称:").pack(side=tk.LEFT)
self.entry_name_query = tk.Entry(query_frame)
self.entry_name_query.pack(side=tk.LEFT, padx=(5, 0)) # 为输入框之间添加一点水平间隔
tk.Label(query_frame, text="颜色:").pack(side=tk.LEFT)
self.entry_color_query = tk.Entry(query_frame)
self.entry_color_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="品牌:").pack(side=tk.LEFT)
self.entry_brand_query = tk.Entry(query_frame)
self.entry_brand_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="价格:").pack(side=tk.LEFT)
self.entry_price_query = tk.Entry(query_frame)
self.entry_price_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="生产日期:").pack(side=tk.LEFT)
self.entry_production_date_query = tk.Entry(query_frame)
self.entry_production_date_query.pack(side=tk.LEFT)
tk.Button(query_frame, text="查询", command=self.query_jiaju_condition).pack(side=tk.LEFT, padx=10)
self.query_all_jiaju() # 初始化加载所有数据
def query_all_jiaju(self):
self.tree.delete(*self.tree.get_children())
self.cursor.execute("SELECT * FROM jia_ju")
rows = self.cursor.fetchall()
for row in rows:
self.tree.insert('', tk.END, values=row)
def add_jiaju(self): def add_jiaju_popup(self):
def submit(): def submit_add():
# 获取用户输入
name = entry_name.get() name = entry_name.get()
color = entry_color.get() color = entry_color.get()
brand = entry_brand.get() brand = entry_brand.get()
price = entry_price.get() price = entry_price.get()
production_date = entry_production_date.get() production_date = entry_production_date.get()
# 插入数据库操作
sql = f"INSERT INTO jia_ju(name, color, brand, price, production_date) VALUES ('{name}', '{color}', '{brand}', {price}, '{production_date}')" sql = f"INSERT INTO jia_ju(name, color, brand, price, production_date) VALUES ('{name}', '{color}', '{brand}', {price}, '{production_date}')"
try: try:
self.cursor.execute(sql) self.cursor.execute(sql)
self.conn.commit() self.conn.commit()
messagebox.showinfo("成功", "家居信息录入成功!") messagebox.showinfo("成功", "家居信息录入成功!")
add_window.destroy() # 关闭弹窗后刷新列表
self.query_all_jiaju()
except Exception as e: except Exception as e:
messagebox.showerror("错误", f"录入失败: {e}") messagebox.showerror("错误", f"录入失败: {e}")
finally:
add_window.destroy() # 关闭对话框
add_window = tk.Toplevel(self.root) add_window = tk.Toplevel(self.root)
add_window.title("录入家居信息") add_window.title("录入家居信息")
@ -70,63 +124,37 @@ class JiaJuPage:
tk.Label(add_window, text="生产日期:").pack() tk.Label(add_window, text="生产日期:").pack()
entry_production_date = tk.Entry(add_window) entry_production_date = tk.Entry(add_window)
entry_production_date.pack() entry_production_date.pack()
tk.Button(add_window, text="提交", command=submit).pack() tk.Button(add_window, text="提交", command=submit_add).pack()
def query_jiaju(self): def delete_selected_jiaju(self):
self.cursor.execute("SELECT * FROM jia_ju") selected_items = self.tree.selection()
results = self.cursor.fetchall() if not selected_items:
if results: messagebox.showwarning("警告", "请先选择要删除的家居项!")
result_text = "\n".join([str(row) for row in results]) return
messagebox.showinfo("查询结果", result_text) for item in selected_items:
else: item_id = self.tree.item(item)['values'][0]
messagebox.showinfo("查询结果", "无数据")
def delete_jiaju(self):
def confirm_delete():
item_id = entry_id.get()
# 执行删除操作
sql = f"DELETE FROM jia_ju WHERE id={item_id}" sql = f"DELETE FROM jia_ju WHERE id={item_id}"
try: try:
self.cursor.execute(sql) self.cursor.execute(sql)
self.conn.commit() self.conn.commit()
messagebox.showinfo("成功", "家居信息已删除!")
except Exception as e: except Exception as e:
messagebox.showerror("错误", f"删除失败: {e}") messagebox.showerror("错误", f"删除失败: {e}")
finally: self.conn.rollback()
delete_window.destroy() return
messagebox.showinfo("成功", "选中的家居信息已删除!")
delete_window = tk.Toplevel(self.root) self.query_all_jiaju() # 刷新列表
delete_window.title("删除家居")
tk.Label(delete_window, text="请输入家居ID:").pack() def update_selected_jiaju_popup(self):
entry_id = tk.Entry(delete_window) selected_items = self.tree.selection()
entry_id.pack() if not selected_items:
tk.Button(delete_window, text="确认删除", command=confirm_delete).pack() messagebox.showwarning("警告", "请先选择要修改的家居项!")
return
def update_jiaju(self):
def fetch_jiaju_info(): item = selected_items[0] # 假设一次只修改一项
item_id = entry_id.get() item_values = self.tree.item(item)['values']
sql = f"SELECT * FROM jia_ju WHERE id={item_id}" item_id = item_values[0]
try:
self.cursor.execute(sql)
result = self.cursor.fetchone()
if result:
entry_name.delete(0, tk.END)
entry_name.insert(tk.END, result[1])
entry_color.delete(0, tk.END)
entry_color.insert(tk.END, result[2])
entry_brand.delete(0, tk.END)
entry_brand.insert(tk.END, result[3])
entry_price.delete(0, tk.END)
entry_price.insert(tk.END, str(result[4]))
entry_production_date.delete(0, tk.END)
entry_production_date.insert(tk.END, result[5])
else:
messagebox.showinfo("查询结果", "未找到该家居信息")
except Exception as e:
messagebox.showerror("错误", f"查询失败: {e}")
def submit_update(): def submit_update():
item_id = entry_id.get()
name = entry_name.get() name = entry_name.get()
color = entry_color.get() color = entry_color.get()
brand = entry_brand.get() brand = entry_brand.get()
@ -137,46 +165,75 @@ class JiaJuPage:
self.cursor.execute(sql) self.cursor.execute(sql)
self.conn.commit() self.conn.commit()
messagebox.showinfo("成功", "家居信息已更新!") messagebox.showinfo("成功", "家居信息已更新!")
update_window.destroy() # 关闭弹窗后刷新列表
self.query_all_jiaju()
except Exception as e: except Exception as e:
messagebox.showerror("错误", f"更新失败: {e}") messagebox.showerror("错误", f"更新失败: {e}")
finally:
update_window.destroy()
update_window = tk.Toplevel(self.root) update_window = tk.Toplevel(self.root)
update_window.title("修改家居信息") update_window.title("修改家居信息")
tk.Label(update_window, text="请输入家居ID:").pack()
entry_id = tk.Entry(update_window)
entry_id.pack()
tk.Button(update_window, text="查询", command=fetch_jiaju_info).pack()
tk.Label(update_window, text="名称:").pack() tk.Label(update_window, text="名称:").pack()
entry_name = tk.Entry(update_window) entry_name = tk.Entry(update_window)
entry_name.insert(tk.END, item_values[1]) # 预填充现有值
entry_name.pack() entry_name.pack()
tk.Label(update_window, text="颜色:").pack() tk.Label(update_window, text="颜色:").pack()
entry_color = tk.Entry(update_window) entry_color = tk.Entry(update_window)
entry_color.insert(tk.END, item_values[2])
entry_color.pack() entry_color.pack()
tk.Label(update_window, text="品牌:").pack() tk.Label(update_window, text="品牌:").pack()
entry_brand = tk.Entry(update_window) entry_brand = tk.Entry(update_window)
entry_brand.insert(tk.END, item_values[3])
entry_brand.pack() entry_brand.pack()
tk.Label(update_window, text="价格:").pack() tk.Label(update_window, text="价格:").pack()
entry_price = tk.Entry(update_window) entry_price = tk.Entry(update_window)
entry_price.insert(tk.END, item_values[4])
entry_price.pack() entry_price.pack()
tk.Label(update_window, text="生产日期:").pack() tk.Label(update_window, text="生产日期:").pack()
entry_production_date = tk.Entry(update_window) entry_production_date = tk.Entry(update_window)
entry_production_date.insert(tk.END, item_values[5])
entry_production_date.pack() entry_production_date.pack()
tk.Button(update_window, text="提交修改", command=submit_update).pack() tk.Button(update_window, text="提交修改", command=submit_update).pack()
def query_jiaju_condition(self):
name_cond = self.entry_name_query.get().strip()
color_cond = self.entry_color_query.get().strip()
brand_cond = self.entry_brand_query.get().strip()
price_cond = self.entry_price_query.get().strip()
production_date_cond = self.entry_production_date_query.get().strip()
conditions = []
if name_cond:
conditions.append(f"name LIKE '%{name_cond}%'")
if color_cond:
conditions.append(f"color LIKE '%{color_cond}%'")
if brand_cond:
conditions.append(f"brand LIKE '%{brand_cond}%'")
if price_cond.isdigit(): # 确保价格是数字
conditions.append(f"price = {price_cond}")
if production_date_cond:
conditions.append(f"production_date = '{production_date_cond}'")
where_clause = ' AND '.join(conditions) if conditions else '1=1'
sql = f"SELECT * FROM jia_ju WHERE {where_clause}"
try:
self.cursor.execute(sql)
rows = self.cursor.fetchall()
self.tree.delete(*self.tree.get_children())
for row in rows:
self.tree.insert('', tk.END, values=row)
except Exception as e:
messagebox.showerror("错误", f"查询失败: {e}")
self.conn.rollback()
def close_conn(self): def close_conn(self):
# 关闭数据库连接
self.cursor.close() self.cursor.close()
self.conn.close() self.conn.close()
self.root.destroy()
if __name__ == '__main__': if __name__ == '__main__':
root = tk.Tk() root = tk.Tk()
app = JiaJuPage(root) app = JiaJuPage(root)
# 确保在程序结束时关闭数据库连接
root.protocol("WM_DELETE_WINDOW", app.close_conn) root.protocol("WM_DELETE_WINDOW", app.close_conn)
root.mainloop() root.mainloop()
Loading…
Cancel
Save