main
123 6 months ago
parent a8838866e5
commit 21589bc701

@ -1,45 +0,0 @@
import tkinter as tk
import tkinter.messagebox
from 主页面 import MainPage
#from 家居信息 import JiaJuPage
class LoginPage:
def __init__(self,master):
self.root = master
self.page = tk.Frame(self.root)
self.page.pack()
self.root.title('智能家居系统')
self.root.geometry("300x180")
self.username = tk.StringVar()
self.password = tk.StringVar()
tk.Label(self.page).grid(row=0, column=0)
tk.Label(self.page, text='账户').grid(row=1,column=0)
tk.Entry(self.page, textvariable=self.username).grid(row=1, column=1)
tk.Label(self.page, text='密码').grid(row=2, column=0)
tk.Entry(self.page, textvariable=self.password).grid(row=2, column=1, pady=10)
tk.Button(self.page, text='登录', command=self.login_check).grid(row=3, column=0, pady=10)
tk.Button(self.page, text='退出', command=root.quit).grid(row=3, column=1, pady=10,stick=tk.E)
def login_check(self):
name = self.username.get()
pwd = self.password.get()
if name == '123' or pwd == '123' :
tkinter.messagebox.showinfo(title='恭喜', message='登录成功')
self.page.destroy()
#JiaJuPage(self.root)
MainPage(self.root)
else:
tkinter.messagebox.showinfo(title='错误', message='账户或密码错误')
if __name__ == '__main__':
root = tk.Tk()
root.title("智能家居系统")
LoginPage(root)
root.mainloop()

@ -1,35 +0,0 @@
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()

@ -1,89 +0,0 @@
from datetime import datetime
from flask import request, jsonify
from flask import *
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:LH20021212@localhost:3306/智能家居系统'
db = SQLAlchemy(app)
try:
with app.app_context():
# 尝试连接数据库
db.create_all()
print("数据库连接成功!")
except Exception as e:
print(f"数据库连接失败: {str(e)}")
class JiaJu(db.Model):
_tablename_ = 'JiaJu' # 这里应该是__tablename__
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
color = db.Column(db.String(50))
brand = db.Column(db.String(50))
price = db.Column(db.Float, nullable=False)
production_date = db.Column(db.Date, nullable=False)
#增
@app.route('/add_jiaju', methods=['POST'])
def add_jiaju():
data = request.get_json() # 假设前端发送的是JSON数据
new_jiaju = JiaJu(
name=data['name'],
color=data.get('color'), # 如果color可选则使用get
brand=data.get('brand'),
price=data['price'],
production_date=datetime.strptime(data['production_date'], '%Y-%m-%d') # 假定日期格式为YYYY-MM-DD
)
db.session.add(new_jiaju)
db.session.commit()
return jsonify({"message": "家居添加成功"}), 201
#查
@app.route('/jiaju', methods=['GET'])
def get_all_jiaju():
jiaju_list = JiaJu.query.all()
result = [{"id": item.id, "name": item.name, "color": item.color, "brand": item.brand,
"price": item.price, "production_date": item.production_date.strftime('%Y-%m-%d')} for item in jiaju_list]
return jsonify(result)
#获取
@app.route('/jiaju/<int:jiaju_id>', methods=['GET'])
def get_jiaju(jiaju_id):
jiaju = JiaJu.query.get_or_404(jiaju_id)
return jsonify({
"id": jiaju.id,
"name": jiaju.name,
"color": jiaju.color,
"brand": jiaju.brand,
"price": jiaju.price,
"production_date": jiaju.production_date.strftime('%Y-%m-%d')
})
#更
@app.route('/jiaju/<int:jiaju_id>', methods=['PUT'])
def update_jiaju(jiaju_id):
jiaju = JiaJu.query.get_or_404(jiaju_id)
data = request.get_json()
if 'name' in data:
jiaju.name = data['name']
if 'color' in data:
jiaju.color = data['color']
if 'brand' in data:
jiaju.brand = data['brand']
if 'price' in data:
jiaju.price = data['price']
if 'production_date' in data:
jiaju.production_date = datetime.strptime(data['production_date'], '%Y-%m-%d')
db.session.commit()
return jsonify({"message": "家居信息更新成功"})
#删
@app.route('/jiaju/<int:jiaju_id>', methods=['DELETE'])
def delete_jiaju(jiaju_id):
jiaju = JiaJu.query.get_or_404(jiaju_id)
db.session.delete(jiaju)
db.session.commit()
return jsonify({"message": "家居删除成功"})

@ -1,239 +0,0 @@
import tkinter as tk
from tkinter import ttk, messagebox
import pymysql
#from 主页面 import MainPage
class JiaJuPage:
def __init__(self, master):
self.root = master
self.root.title("智能家居系统 - 家居管理")
self.root.geometry('1000x700')
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)
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_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 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):
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,136 +0,0 @@
import tkinter as tk
from tkinter import ttk
from tkinter import Toplevel
import random
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# 初始化全局变量
root = tk.Tk()
root.title("智能家居系统-环境监测数据展示")
# 数据结构和全局变量
data_records = []
plot_window = None
figure = None
canvas = None
axs = None
# 函数定义
def setup_ui():
"""UI设置"""
root.geometry("800x600")
def simulate_data():
"""数据模拟"""
global temperature, humidity, light_intensity, pm2_5
temperature = random.uniform(-15, 45)
humidity = random.uniform(0, 100)
light_intensity = random.randint(100, 1000)
pm2_5 = random.uniform(0, 300) # 假定PM2.5浓度范围
data_records.append({
"序号": len(data_records) + 1,
"温度": temperature,
"湿度": humidity,
"光照强度": light_intensity,
"PM2.5": pm2_5
})
update_treeview()
if plot_window and figure and canvas:
update_plots()
def update_treeview():
"""更新表格视图包含PM2.5列及其等级"""
treeview.delete(*treeview.get_children())
for record in data_records:
pm2_5_level_tag = get_pm2_5_level(record["PM2.5"])
treeview.insert("", tk.END, values=(
record["序号"],
f"{record['温度']:.2f} °C",
f"{record['湿度']:.2f}%",
f"{record['光照强度']} lux",
f"{record['PM2.5']:.2f} µg/m³{pm2_5_level_tag}"
))
def update_data_and_display():
"""定时更新数据"""
simulate_data()
root.after(5000, update_data_and_display)
def on_plot_window_close():
"""图表窗口关闭事件处理"""
global plot_window
plot_window.destroy()
plot_window = None
def show_plot_window():
"""显示图表窗口更新图表以包含PM2.5"""
global plot_window, figure, axs, canvas
if not plot_window:
plot_window = Toplevel(root)
plot_window.protocol("WM_DELETE_WINDOW", on_plot_window_close)
plot_window.title("智能家居系统-环境数据走势图")
figure, axs = plt.subplots(4, 1, figsize=(6, 10), sharex=True)
figure.suptitle('智能家居系统-环境数据走势图')
keys = ["温度", "湿度", "光照强度", "PM2.5"]
for i, key in enumerate(keys):
axs[i].set_title(f'{key}变化')
axs[i].plot([r['序号'] for r in data_records], [r[key] for r in data_records], label=key)
axs[i].legend()
axs[i].grid(True)
canvas = FigureCanvasTkAgg(figure, master=plot_window)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def update_plots():
"""更新图表包含PM2.5图"""
for ax, key in zip(axs, ["温度", "湿度", "光照强度", "PM2.5"]):
ax.clear()
ax.plot([r['序号'] for r in data_records], [r[key] for r in data_records], label=key)
ax.set_title(f'{key}变化')
ax.legend()
ax.grid(True)
canvas.draw_idle()
# 设置matplotlib字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# UI组件初始化添加PM2.5列
treeview = ttk.Treeview(root, columns=("序号", "温度", "湿度", "光照强度", "PM2.5"), show="headings")
treeview.column("序号", width=50, anchor=tk.CENTER)
treeview.column("温度", width=100, anchor=tk.CENTER)
treeview.column("湿度", width=100, anchor=tk.CENTER)
treeview.column("光照强度", width=120, anchor=tk.CENTER)
treeview.column("PM2.5", width=100, anchor=tk.CENTER)
treeview.heading("序号", text="序号")
treeview.heading("温度", text="温度")
treeview.heading("湿度", text="湿度")
treeview.heading("光照强度", text="光照强度")
treeview.heading("PM2.5", text="PM2.5")
treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
plot_button = ttk.Button(root, text="查看走势图", command=show_plot_window)
plot_button.pack(pady=10)
setup_ui()
def get_pm2_5_level(pm2_5_value):
"""根据PM2.5值返回其等级标签"""
if 0 <= pm2_5_value <= 35:
return "(优)"
elif 35 < pm2_5_value <= 75:
return "(良)"
elif 75 < pm2_5_value <= 115:
return "(轻度污染)"
elif 115 < pm2_5_value <= 150:
return "(中度污染)"
elif 150 < pm2_5_value <= 250:
return "(重度污染)"
else:
return "(严重污染)"
# 主循环启动
update_data_and_display()
root.mainloop()

@ -1,111 +0,0 @@
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from tkinter import Toplevel
import random
import time
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class EnvironmentMonitorApp:
def __init__(self, root):
self.root = root
self.root.title("环境监测数据展示")
self.setup_ui()
self.data_records = [] # 保存所有监测记录
self.plot_window = None # 初始化图表窗口变量
self.figure = None # 初始化图表figure变量
self.canvas = None # 初始化图表canvas变量
self.axs = None # 初始化子图变量
self.root.after(5000, self.update_data_and_display) # 每5秒更新一次数据
# 设置matplotlib的字体以支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
def setup_ui(self):
# 调整窗口大小以适应更多数据
self.root.geometry("800x600") # 或根据实际需要调整
self.treeview = ttk.Treeview(self.root, columns=("序号", "温度", "湿度", "光照强度"), show="headings")
self.treeview.column("序号", width=50, anchor=tk.CENTER)
self.treeview.column("温度", width=100, anchor=tk.CENTER)
self.treeview.column("湿度", width=100, anchor=tk.CENTER)
self.treeview.column("光照强度", width=120, anchor=tk.CENTER)
self.treeview.heading("序号", text="序号")
self.treeview.heading("温度", text="温度")
self.treeview.heading("湿度", text="湿度")
self.treeview.heading("光照强度", text="光照强度")
self.treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) # 让Treeview自适应填充空间
self.plot_button = ttk.Button(self.root, text="查看走势图", command=self.show_plot_window)
self.plot_button.pack(pady=10) # 也可以根据需要调整按钮的位置
def simulate_data(self):
self.temperature = random.uniform(-15, 45)#18-25
self.humidity = random.uniform(0, 100)#30-60
self.light_intensity = random.randint(100, 1000)#300-500
self.data_records.append({
"序号": len(self.data_records) + 1,
"温度": self.temperature,
"湿度": self.humidity,
"光照强度": self.light_intensity
})
self.update_treeview()
if self.plot_window and self.figure and self.canvas:
self.update_plots()
def update_treeview(self):
# 更新表格数据,每行包含一条完整记录
self.treeview.delete(*self.treeview.get_children())
for record in self.data_records:
self.treeview.insert("", tk.END, values=(
record["序号"],
f"{record['温度']:.2f} °C",
f"{record['湿度']:.2f}%",
f"{record['光照强度']} lux"
))
def update_data_and_display(self):
self.simulate_data()
self.root.after(5000, self.update_data_and_display)
def on_plot_window_close(self):
self.plot_window.destroy()
self.plot_window = None # 关闭窗口后重置plot_window为None以便下次能重新创建
def show_plot_window(self):
if not self.plot_window:
self.plot_window = Toplevel(self.root)
self.plot_window.protocol("WM_DELETE_WINDOW", self.on_plot_window_close) # 添加关闭窗口的回调
self.plot_window.title("环境数据走势图")
self.figure, self.axs = plt.subplots(3, 1, figsize=(6, 8), sharex=True)
self.figure.suptitle('环境数据实时走势图')
self.axs[0].set_title('温度变化')
self.axs[1].set_title('湿度变化')
self.axs[2].set_title('光照强度变化')
for ax in self.axs:
ax.legend()
ax.grid(True)
self.canvas = FigureCanvasTkAgg(self.figure, master=self.plot_window)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def update_plots(self):
for ax, key in zip(self.axs, ["温度", "湿度", "光照强度"]):
ax.clear() # 清除旧的图表
ax.set_title(f'{key}变化') # 设置子图标题
ax.plot([r['序号'] for r in self.data_records], [r[key] for r in self.data_records], label=key)
ax.legend()
ax.grid(True)
self.canvas.draw_idle() # 更新图表而不重新绘制整个画布
def main():
root = tk.Tk()
app = EnvironmentMonitorApp(root)
root.mainloop()
if __name__ == "__main__":
main()

@ -1,69 +0,0 @@
import tkinter as tk
from tkinter import ttk
import random
import time
# 全局变量
comfortable_temperature_range = (20, 24)
comfortable_humidity_range = (40, 60)
current_temperature = 0
current_humidity = 0
line_number = 0
update_interval = 5000 # 每5秒更新一次
root = None
treeview = None
def reset_conditions():
global current_temperature, current_humidity
current_temperature = random.uniform(-12, 42)
current_humidity = random.uniform(0, 100)
def adjust():
global current_temperature, current_humidity
reset_conditions()
if not comfortable_temperature_range[0] <= current_temperature <= comfortable_temperature_range[1]:
current_temperature = random.uniform(*comfortable_temperature_range)
if not comfortable_humidity_range[0] <= current_humidity <= comfortable_humidity_range[1]:
current_humidity = random.uniform(*comfortable_humidity_range)
return current_temperature, current_humidity
def schedule_update():
"""计划下一次更新"""
global line_number
line_number += 1
initial_temp, initial_humidity = current_temperature, current_humidity
adjusted_temp, adjusted_humidity = adjust()
treeview.insert("", tk.END, values=(line_number,
f"{initial_temp:.2f}°C",
f"{initial_humidity:.2f}%",
f"{adjusted_temp:.2f}°C",
f"{adjusted_humidity:.2f}%"))
# 安排下一次更新
root.after(update_interval, schedule_update)
def main():
global root, treeview
root = tk.Tk()
root.title("智能家居系统-空调自动调节系统")
root.geometry("800x600")
treeview = ttk.Treeview(root,
columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"),
show="headings")
treeview.heading("编号", text="编号")
treeview.heading("初始温度", text="初始温度")
treeview.heading("初始湿度", text="初始湿度")
treeview.heading("调节后温度", text="调节后温度")
treeview.heading("调节后湿度", text="调节后湿度")
for col in treeview['columns']:
treeview.column(col, width=80, anchor=tk.CENTER)
treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
schedule_update() # 安排首次更新
root.mainloop()
if __name__ == "__main__":
main()

@ -1,67 +0,0 @@
import tkinter as tk
from tkinter import ttk
import random
import time
class AirConditioner:
def __init__(self):
self.comfortable_temperature_range = (20, 24) # 添加舒适温度范围
self.comfortable_humidity_range = (40, 60) # 添加舒适湿度范围
self.reset_conditions()
def reset_conditions(self):
self.current_temperature = random.uniform(-12, 42)
self.current_humidity = random.uniform(0, 100)
def adjust(self):
self.reset_conditions() # 获取新的初始温度和湿度
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]:
self.current_temperature = random.uniform(*self.comfortable_temperature_range)
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
self.current_humidity = random.uniform(*self.comfortable_humidity_range)
return self.current_temperature, self.current_humidity # 返回调节后的温度和湿度
class ACApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("空调自动调节系统")
self.geometry("800x600")
self.treeview = ttk.Treeview(self,
columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"),
show="headings")
self.treeview.heading("编号", text="编号")
self.treeview.heading("初始温度", text="初始温度")
self.treeview.heading("初始湿度", text="初始湿度")
self.treeview.heading("调节后温度", text="调节后温度")
self.treeview.heading("调节后湿度", text="调节后湿度")
for col in self.treeview['columns']:
self.treeview.column(col, width=80, anchor=tk.CENTER)
self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
self.aircon = AirConditioner()
self.line_number = 0
self.is_adjusted = False
self.update_interval = 5000 # 每5秒更新一次
self.schedule_update() # 安排首次更新
self.treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
def schedule_update(self):
"""计划下一次更新"""
self.line_number += 1
initial_temp, initial_humidity = self.aircon.current_temperature, self.aircon.current_humidity
adjusted_temp, adjusted_humidity = self.aircon.adjust()
self.treeview.insert("", tk.END, values=(self.line_number,
f"{initial_temp:.1f}°C",
f"{initial_humidity:.1f}%",
f"{adjusted_temp:.1f}°C",
f"{adjusted_humidity:.1f}%"))
# 安排下一次更新
self.after(self.update_interval, self.schedule_update)
if __name__ == "__main__":
app = ACApp()
app.mainloop()

@ -9,15 +9,14 @@ def login_check(root, username_var, password_var):
if name == '123' and pwd == '123': if name == '123' and pwd == '123':
messagebox.showinfo(title='恭喜', message='登录成功') messagebox.showinfo(title='恭喜', message='登录成功')
xiaohui() xiaohui()
# MainPage(root) # 如果需要,取消注释此行并确保已正确导入主页面模块
else: else:
messagebox.showinfo(title='错误', message='账户或密码错误') messagebox.showinfo(title='错误', message='账户或密码错误,请重新登录')
def main(): def main():
global root global root
root = tk.Tk() root = tk.Tk()
root.title('智能家居系统-登录界面') root.title('智能家居系统-登录界面')
root.geometry("300x180") root.geometry("200x180")
username_var = tk.StringVar() username_var = tk.StringVar()
password_var = tk.StringVar() password_var = tk.StringVar()

@ -5,30 +5,16 @@ import random
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# 初始化全局变量
root = tk.Tk()
root.title("智能家居系统-环境监测数据展示")
# 数据结构和全局变量
data_records = []
plot_window = None
figure = None
canvas = None
axs = None
# 函数定义
def setup_ui(): def setup_ui():
"""UI设置"""
root.geometry("800x600") root.geometry("800x600")
def simulate_data(): def simulate_data():
"""数据模拟"""
global temperature, humidity, light_intensity, pm2_5 global temperature, humidity, light_intensity, pm2_5
temperature = random.uniform(-15, 45) temperature = random.uniform(-15, 45)
humidity = random.uniform(0, 100) humidity = random.uniform(0, 100)
light_intensity = random.randint(100, 5000) light_intensity = random.randint(100, 5000)
pm2_5 = random.uniform(0, 300) # 假定PM2.5浓度范围 pm2_5 = random.uniform(0, 300)
data_records.append({ data_records.append({
"序号": len(data_records) + 1, "序号": len(data_records) + 1,
"温度": temperature, "温度": temperature,
@ -54,7 +40,6 @@ def update_treeview():
)) ))
def update_data_and_display(): def update_data_and_display():
"""定时更新数据"""
simulate_data() simulate_data()
root.after(5000, update_data_and_display) root.after(5000, update_data_and_display)
@ -65,7 +50,6 @@ def on_plot_window_close():
plot_window = None plot_window = None
def show_plot_window(): def show_plot_window():
"""显示图表窗口更新图表以包含PM2.5"""
global plot_window, figure, axs, canvas global plot_window, figure, axs, canvas
if not plot_window: if not plot_window:
plot_window = Toplevel(root) plot_window = Toplevel(root)
@ -84,7 +68,6 @@ def show_plot_window():
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def update_plots(): def update_plots():
"""更新图表包含PM2.5图"""
for ax, key in zip(axs, ["温度", "湿度", "光照强度", "PM2.5"]): for ax, key in zip(axs, ["温度", "湿度", "光照强度", "PM2.5"]):
ax.clear() ax.clear()
ax.plot([r['序号'] for r in data_records], [r[key] for r in data_records], label=key) ax.plot([r['序号'] for r in data_records], [r[key] for r in data_records], label=key)
@ -93,11 +76,39 @@ def update_plots():
ax.grid(True) ax.grid(True)
canvas.draw_idle() canvas.draw_idle()
# 设置matplotlib字体
def get_pm2_5_level(pm2_5_value):
if 0 <= pm2_5_value <= 35:
return "(优)"
elif 35 < pm2_5_value <= 75:
return "(良)"
elif 75 < pm2_5_value <= 115:
return "(轻度污染)"
elif 115 < pm2_5_value <= 150:
return "(中度污染)"
elif 150 < pm2_5_value <= 250:
return "(重度污染)"
else:
return "(严重污染)"
plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False plt.rcParams['axes.unicode_minus'] = False
def aaa():
global root,data_records ,plot_window,figure,cnvasa ,axs
root = tk.Tk()
root.title("智能家居系统-环境监测数据展示")
data_records = []
plot_window = None
figure = None
cnvasa = None
axs = None
# UI组件初始化添加PM2.5列 # UI组件初始化添加PM2.5列
global treeview
treeview = ttk.Treeview(root, columns=("序号", "温度", "湿度", "光照强度", "PM2.5"), show="headings") treeview = ttk.Treeview(root, columns=("序号", "温度", "湿度", "光照强度", "PM2.5"), show="headings")
treeview.column("序号", width=50, anchor=tk.CENTER) treeview.column("序号", width=50, anchor=tk.CENTER)
treeview.column("温度", width=100, anchor=tk.CENTER) treeview.column("温度", width=100, anchor=tk.CENTER)
@ -113,25 +124,14 @@ treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
plot_button = ttk.Button(root, text="监测走势图", command=show_plot_window) plot_button = ttk.Button(root, text="监测走势图", command=show_plot_window)
plot_button.pack(pady=10) plot_button.pack(pady=10)
plot_button = ttk.Button(root, text="返回", command=root.destroy)
plot_button.pack(pady=10)
setup_ui() setup_ui()
def get_pm2_5_level(pm2_5_value):
"""根据PM2.5值返回其等级标签"""
if 0 <= pm2_5_value <= 35:
return "(优)"
elif 35 < pm2_5_value <= 75:
return "(良)"
elif 75 < pm2_5_value <= 115:
return "(轻度污染)"
elif 115 < pm2_5_value <= 150:
return "(中度污染)"
elif 150 < pm2_5_value <= 250:
return "(重度污染)"
else:
return "(严重污染)"
# 主循环启动
update_data_and_display() update_data_and_display()
root.mainloop() root.mainloop()
if __name__ == "__main__":
aaa()

@ -3,17 +3,13 @@ from tkinter import ttk
import pymysql import pymysql
from tkinter import messagebox from tkinter import messagebox
# 初始化数据库连接
def init_db_connection(): def init_db_connection():
global conn, cursor global conn, cursor
conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统', charset='utf8mb4') conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统', charset='utf8mb4')
cursor = conn.cursor() cursor = conn.cursor()
# 创建主界面
def create_main_window(): def create_main_window():
global root, tree, entry_name_query, entry_color_query, entry_brand_query, entry_price_query, entry_production_date_query, button_frame, query_frame global root, tree, entry_name_query, entry_color_query, entry_brand_query, entry_price_query, entry_production_date_query, button_frame, query_frame
@ -28,11 +24,10 @@ def create_main_window():
root.mainloop() root.mainloop()
# 创建界面组件
def create_widgets(): def create_widgets():
global tree, entry_name_query, entry_color_query, entry_brand_query, entry_price_query, entry_production_date_query, button_frame, query_frame global tree, entry_name_query, entry_color_query, entry_brand_query, entry_price_query, entry_production_date_query, button_frame, query_frame
# 表格和滚动条
frame = tk.Frame(root) frame = tk.Frame(root)
frame.pack(fill=tk.BOTH, expand=True) frame.pack(fill=tk.BOTH, expand=True)
scrollbar_y = tk.Scrollbar(frame, orient=tk.VERTICAL) scrollbar_y = tk.Scrollbar(frame, orient=tk.VERTICAL)
@ -61,7 +56,6 @@ def create_widgets():
scrollbar_x.config(command=tree.xview) scrollbar_x.config(command=tree.xview)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X) scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
# 按钮区域
button_frame = tk.Frame(root) button_frame = tk.Frame(root)
button_frame.pack(pady=10) button_frame.pack(pady=10)
tk.Button(button_frame, text="添加家居", command=add_jiaju_popup).pack(side=tk.LEFT, padx=10) tk.Button(button_frame, text="添加家居", command=add_jiaju_popup).pack(side=tk.LEFT, padx=10)
@ -70,7 +64,6 @@ def create_widgets():
tk.Button(button_frame, text="查询所有", command=query_all_jiaju).pack(side=tk.LEFT, padx=10) tk.Button(button_frame, text="查询所有", command=query_all_jiaju).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="返回", command=root.destroy).pack(side=tk.LEFT, padx=10) tk.Button(button_frame, text="返回", command=root.destroy).pack(side=tk.LEFT, padx=10)
# 查询条件输入框区域
query_frame = tk.Frame(root) query_frame = tk.Frame(root)
query_frame.pack(pady=(10, 0)) query_frame.pack(pady=(10, 0))
tk.Label(query_frame, text="名称:").pack(side=tk.LEFT) tk.Label(query_frame, text="名称:").pack(side=tk.LEFT)
@ -93,16 +86,7 @@ def create_widgets():
query_all_jiaju() query_all_jiaju()
# 查询所有家居信息
def query_all_jiaju():
tree.delete(*tree.get_children())
cursor.execute("SELECT * FROM jia_ju")
rows = cursor.fetchall()
for row in rows:
tree.insert('', tk.END, values=row)
# 添加家居弹窗
def add_jiaju_popup(): def add_jiaju_popup():
def submit_add(): def submit_add():
name = entry_name.get() name = entry_name.get()
@ -139,7 +123,7 @@ def add_jiaju_popup():
entry_production_date.pack() entry_production_date.pack()
tk.Button(add_window, text="提交", command=submit_add).pack() tk.Button(add_window, text="提交", command=submit_add).pack()
# 删除选中家居
def delete_selected_jiaju(self): def delete_selected_jiaju(self):
selected_items = self.tree.selection() selected_items = self.tree.selection()
if not selected_items: if not selected_items:
@ -158,7 +142,7 @@ def delete_selected_jiaju(self):
messagebox.showinfo("成功", "选中的家居信息已删除!") messagebox.showinfo("成功", "选中的家居信息已删除!")
self.query_all_jiaju() # 刷新列表 self.query_all_jiaju() # 刷新列表
# 修改选中家居弹窗
def update_selected_jiaju_popup(): def update_selected_jiaju_popup():
selected_items = tree.selection() selected_items = tree.selection()
if not selected_items: if not selected_items:
@ -209,7 +193,7 @@ def update_selected_jiaju_popup():
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(): def query_jiaju_condition():
name_cond = entry_name_query.get().strip() name_cond = entry_name_query.get().strip()
color_cond = entry_color_query.get().strip() color_cond = entry_color_query.get().strip()
@ -242,15 +226,19 @@ def query_jiaju_condition():
messagebox.showerror("错误", f"查询失败: {e}") messagebox.showerror("错误", f"查询失败: {e}")
conn.rollback() conn.rollback()
# 关闭数据库连接
def query_all_jiaju():
tree.delete(*tree.get_children())
cursor.execute("SELECT * FROM jia_ju")
rows = cursor.fetchall()
for row in rows:
tree.insert('', tk.END, values=row)
def close_conn(): def close_conn():
cursor.close() cursor.close()
conn.close() conn.close()
root.destroy() root.destroy()
if __name__ == '__main__': if __name__ == '__main__':
create_main_window() create_main_window()

@ -2,26 +2,28 @@ import tkinter as tk
from tkinter import messagebox from tkinter import messagebox
from JJXX import create_main_window from JJXX import create_main_window
from HJJC import aaa
def create_main_page(root): def create_main_page(root):
# 创建主页面元素
home_info_title = tk.Label(root, text="主页面", font=("Helvetica", 16)) home_info_title = tk.Label(root, text="功能", font=("Helvetica", 16))
home_info_title.pack(pady=20) home_info_title.pack(pady=20)
# 创建并绑定按钮点击事件,用于显示家居信息
goto_jiaju_button = tk.Button(root, text="家居信息", command=lambda: JiaJuInfoPage(root)) goto_jiaju_button = tk.Button(root, text="家居信息", command=lambda: JiaJuInfoPage(root))
goto_jiaju_button.pack(pady=10) goto_jiaju_button.pack(pady=10)
goto_jiance_button = tk.Button(root, text="环境监测", command=lambda: JianCeInfoPage(root))
goto_jiance_button.pack(pady=10)
def JiaJuInfoPage(master): def JiaJuInfoPage(master):
# 直接在这里创建家居信息页面,而不是通过类实例化
# 注意此处简化处理未完全实现JiaJuPage逻辑仅为示例
create_main_window() create_main_window()
# 根据实际情况调整窗口大小或其他UI元素
def JianCeInfoPage(master):
aaa()
def a(): def a():
root = tk.Tk() root = tk.Tk()
root.title('智能家居系统-主界面')
root.geometry('600x400') root.geometry('600x400')
create_main_page(root) create_main_page(root)
root.mainloop() root.mainloop()

@ -1 +0,0 @@
17.5219813233319,10.705621045530922

@ -1,35 +0,0 @@
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()

@ -1,239 +0,0 @@
import tkinter as tk
from tkinter import ttk, messagebox
import pymysql
#from 主页面 import MainPage
class JiaJuPage:
def __init__(self, master):
self.root = master
self.root.title("智能家居系统 - 家居管理")
self.root.geometry('1000x700')
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)
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_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 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):
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()

@ -11,7 +11,6 @@ db = SQLAlchemy(app)
try: try:
with app.app_context(): with app.app_context():
# 尝试连接数据库
db.create_all() db.create_all()
print("数据库连接成功!") print("数据库连接成功!")
@ -21,7 +20,7 @@ except Exception as e:
class JiaJu(db.Model): class JiaJu(db.Model):
_tablename_ = 'JiaJu' # 这里应该是__tablename__ _tablename_ = 'JiaJu'
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False) name = db.Column(db.String(100), nullable=False)
color = db.Column(db.String(50)) color = db.Column(db.String(50))
@ -29,61 +28,61 @@ class JiaJu(db.Model):
price = db.Column(db.Float, nullable=False) price = db.Column(db.Float, nullable=False)
production_date = db.Column(db.Date, nullable=False) production_date = db.Column(db.Date, nullable=False)
# # #
@app.route('/add_jiaju', methods=['POST']) # @app.route('/add_jiaju', methods=['POST'])
def add_jiaju(): # def add_jiaju():
data = request.get_json() # 假设前端发送的是JSON数据 # data = request.get_json()
new_jiaju = JiaJu( # new_jiaju = JiaJu(
name=data['name'], # name=data['name'],
color=data.get('color'), # 如果color可选则使用get # color=data.get('color'),
brand=data.get('brand'), # brand=data.get('brand'),
price=data['price'], # price=data['price'],
production_date=datetime.strptime(data['production_date'], '%Y-%m-%d') # 假定日期格式为YYYY-MM-DD # production_date=datetime.strptime(data['production_date'], '%Y-%m-%d')
) # )
db.session.add(new_jiaju) # db.session.add(new_jiaju)
db.session.commit() # db.session.commit()
return jsonify({"message": "家居添加成功"}), 201 # return jsonify({"message": "家居添加成功"}), 201
# # #
@app.route('/jiaju', methods=['GET']) # @app.route('/jiaju', methods=['GET'])
def get_all_jiaju(): # def get_all_jiaju():
jiaju_list = JiaJu.query.all() # jiaju_list = JiaJu.query.all()
result = [{"id": item.id, "name": item.name, "color": item.color, "brand": item.brand, # result = [{"id": item.id, "name": item.name, "color": item.color, "brand": item.brand,
"price": item.price, "production_date": item.production_date.strftime('%Y-%m-%d')} for item in jiaju_list] # "price": item.price, "production_date": item.production_date.strftime('%Y-%m-%d')} for item in jiaju_list]
return jsonify(result) # return jsonify(result)
#获取 # #获取
@app.route('/jiaju/<int:jiaju_id>', methods=['GET']) # @app.route('/jiaju/<int:jiaju_id>', methods=['GET'])
def get_jiaju(jiaju_id): # def get_jiaju(jiaju_id):
jiaju = JiaJu.query.get_or_404(jiaju_id) # jiaju = JiaJu.query.get_or_404(jiaju_id)
return jsonify({ # return jsonify({
"id": jiaju.id, # "id": jiaju.id,
"name": jiaju.name, # "name": jiaju.name,
"color": jiaju.color, # "color": jiaju.color,
"brand": jiaju.brand, # "brand": jiaju.brand,
"price": jiaju.price, # "price": jiaju.price,
"production_date": jiaju.production_date.strftime('%Y-%m-%d') # "production_date": jiaju.production_date.strftime('%Y-%m-%d')
}) # })
# # #
@app.route('/jiaju/<int:jiaju_id>', methods=['PUT']) # @app.route('/jiaju/<int:jiaju_id>', methods=['PUT'])
def update_jiaju(jiaju_id): # def update_jiaju(jiaju_id):
jiaju = JiaJu.query.get_or_404(jiaju_id) # jiaju = JiaJu.query.get_or_404(jiaju_id)
data = request.get_json() # data = request.get_json()
if 'name' in data: # if 'name' in data:
jiaju.name = data['name'] # jiaju.name = data['name']
if 'color' in data: # if 'color' in data:
jiaju.color = data['color'] # jiaju.color = data['color']
if 'brand' in data: # if 'brand' in data:
jiaju.brand = data['brand'] # jiaju.brand = data['brand']
if 'price' in data: # if 'price' in data:
jiaju.price = data['price'] # jiaju.price = data['price']
if 'production_date' in data: # if 'production_date' in data:
jiaju.production_date = datetime.strptime(data['production_date'], '%Y-%m-%d') # jiaju.production_date = datetime.strptime(data['production_date'], '%Y-%m-%d')
db.session.commit() # db.session.commit()
return jsonify({"message": "家居信息更新成功"}) # return jsonify({"message": "家居信息更新成功"})
# # #
@app.route('/jiaju/<int:jiaju_id>', methods=['DELETE']) # @app.route('/jiaju/<int:jiaju_id>', methods=['DELETE'])
def delete_jiaju(jiaju_id): # def delete_jiaju(jiaju_id):
jiaju = JiaJu.query.get_or_404(jiaju_id) # jiaju = JiaJu.query.get_or_404(jiaju_id)
db.session.delete(jiaju) # db.session.delete(jiaju)
db.session.commit() # db.session.commit()
return jsonify({"message": "家居删除成功"}) # return jsonify({"message": "家居删除成功"})

@ -1,22 +0,0 @@
from flask import Flask
import pymysql
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:LH20021212@localhost:3306/智能家居系统'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Jia():
__tablename__ = '家居信息' # 注意这里使用英文表名
编号 = db.Column(db.Integer, primary_key=True)
名称 = db.Column(db.String(20), nullable=False)
品牌 = db.Column(db.String(20), nullable=False)
颜色 = db.Column(db.String(20), nullable=False)
价格 = db.Column(db.String(20), nullable=False)
生产日期 = db.Column(db.String(20), nullable=False)

@ -1,111 +0,0 @@
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from tkinter import Toplevel
import random
import time
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class EnvironmentMonitorApp:
def __init__(self, root):
self.root = root
self.root.title("环境监测数据展示")
self.setup_ui()
self.data_records = [] # 保存所有监测记录
self.plot_window = None # 初始化图表窗口变量
self.figure = None # 初始化图表figure变量
self.canvas = None # 初始化图表canvas变量
self.axs = None # 初始化子图变量
self.root.after(5000, self.update_data_and_display) # 每5秒更新一次数据
# 设置matplotlib的字体以支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
def setup_ui(self):
# 调整窗口大小以适应更多数据
self.root.geometry("800x600") # 或根据实际需要调整
self.treeview = ttk.Treeview(self.root, columns=("序号", "温度", "湿度", "光照强度"), show="headings")
self.treeview.column("序号", width=50, anchor=tk.CENTER)
self.treeview.column("温度", width=100, anchor=tk.CENTER)
self.treeview.column("湿度", width=100, anchor=tk.CENTER)
self.treeview.column("光照强度", width=120, anchor=tk.CENTER)
self.treeview.heading("序号", text="序号")
self.treeview.heading("温度", text="温度")
self.treeview.heading("湿度", text="湿度")
self.treeview.heading("光照强度", text="光照强度")
self.treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) # 让Treeview自适应填充空间
self.plot_button = ttk.Button(self.root, text="查看走势图", command=self.show_plot_window)
self.plot_button.pack(pady=10) # 也可以根据需要调整按钮的位置
def simulate_data(self):
self.temperature = random.uniform(-15, 45)#18-25
self.humidity = random.uniform(0, 100)#30-60
self.light_intensity = random.randint(100, 1000)#300-500
self.data_records.append({
"序号": len(self.data_records) + 1,
"温度": self.temperature,
"湿度": self.humidity,
"光照强度": self.light_intensity
})
self.update_treeview()
if self.plot_window and self.figure and self.canvas:
self.update_plots()
def update_treeview(self):
# 更新表格数据,每行包含一条完整记录
self.treeview.delete(*self.treeview.get_children())
for record in self.data_records:
self.treeview.insert("", tk.END, values=(
record["序号"],
f"{record['温度']:.2f} °C",
f"{record['湿度']:.2f}%",
f"{record['光照强度']} lux"
))
def update_data_and_display(self):
self.simulate_data()
self.root.after(5000, self.update_data_and_display)
def on_plot_window_close(self):
self.plot_window.destroy()
self.plot_window = None # 关闭窗口后重置plot_window为None以便下次能重新创建
def show_plot_window(self):
if not self.plot_window:
self.plot_window = Toplevel(self.root)
self.plot_window.protocol("WM_DELETE_WINDOW", self.on_plot_window_close) # 添加关闭窗口的回调
self.plot_window.title("环境数据走势图")
self.figure, self.axs = plt.subplots(3, 1, figsize=(6, 8), sharex=True)
self.figure.suptitle('环境数据实时走势图')
self.axs[0].set_title('温度变化')
self.axs[1].set_title('湿度变化')
self.axs[2].set_title('光照强度变化')
for ax in self.axs:
ax.legend()
ax.grid(True)
self.canvas = FigureCanvasTkAgg(self.figure, master=self.plot_window)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def update_plots(self):
for ax, key in zip(self.axs, ["温度", "湿度", "光照强度"]):
ax.clear() # 清除旧的图表
ax.set_title(f'{key}变化') # 设置子图标题
ax.plot([r['序号'] for r in self.data_records], [r[key] for r in self.data_records], label=key)
ax.legend()
ax.grid(True)
self.canvas.draw_idle() # 更新图表而不重新绘制整个画布
def main():
root = tk.Tk()
app = EnvironmentMonitorApp(root)
root.mainloop()
if __name__ == "__main__":
main()

@ -1,44 +0,0 @@
import tkinter as tk
import tkinter.messagebox
from 主页面 import MainPage
class LoginPage:
def __init__(self,master):
self.root = master
self.page = tk.Frame(self.root)
self.page.pack()
self.root.geometry("300x180")
self.username = tk.StringVar()
self.password = tk.StringVar()
tk.Label(self.page).grid(row=0, column=0)
tk.Label(self.page, text='账户').grid(row=1,column=0)
tk.Entry(self.page, textvariable=self.username).grid(row=1, column=1)
tk.Label(self.page, text='密码').grid(row=2, column=0)
tk.Entry(self.page, textvariable=self.password).grid(row=2, column=1, pady=10)
tk.Button(self.page, text='登录', command=self.login_check).grid(row=3, column=0, pady=10)
tk.Button(self.page, text='退出', command=root.quit).grid(row=3, column=1, pady=10,stick=tk.E)
def login_check(self):
name = self.username.get()
pwd = self.password.get()
if name == '123' or pwd == '123' :
tkinter.messagebox.showinfo(title='恭喜', message='登录成功')
self.page.destroy()
#JiaJuPage(self.root)
MainPage(self.root)
else:
tkinter.messagebox.showinfo(title='错误', message='账户或密码错误')
if __name__ == '__main__':
root = tk.Tk()
root.title("智能家居系统-登录页面")
LoginPage(root)
root.mainloop()

@ -1,67 +0,0 @@
import tkinter as tk
from tkinter import ttk
import random
import time
class AirConditioner:
def __init__(self):
self.comfortable_temperature_range = (20, 24) # 添加舒适温度范围
self.comfortable_humidity_range = (40, 60) # 添加舒适湿度范围
self.reset_conditions()
def reset_conditions(self):
self.current_temperature = random.uniform(-12, 42)
self.current_humidity = random.uniform(0, 100)
def adjust(self):
self.reset_conditions() # 获取新的初始温度和湿度
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]:
self.current_temperature = random.uniform(*self.comfortable_temperature_range)
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
self.current_humidity = random.uniform(*self.comfortable_humidity_range)
return self.current_temperature, self.current_humidity # 返回调节后的温度和湿度
class ACApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("空调自动调节系统")
self.geometry("800x600")
self.treeview = ttk.Treeview(self,
columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"),
show="headings")
self.treeview.heading("编号", text="编号")
self.treeview.heading("初始温度", text="初始温度")
self.treeview.heading("初始湿度", text="初始湿度")
self.treeview.heading("调节后温度", text="调节后温度")
self.treeview.heading("调节后湿度", text="调节后湿度")
for col in self.treeview['columns']:
self.treeview.column(col, width=80, anchor=tk.CENTER)
self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
self.aircon = AirConditioner()
self.line_number = 0
self.is_adjusted = False
self.update_interval = 5000 # 每5秒更新一次
self.schedule_update() # 安排首次更新
self.treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
def schedule_update(self):
"""计划下一次更新"""
self.line_number += 1
initial_temp, initial_humidity = self.aircon.current_temperature, self.aircon.current_humidity
adjusted_temp, adjusted_humidity = self.aircon.adjust()
self.treeview.insert("", tk.END, values=(self.line_number,
f"{initial_temp:.1f}°C",
f"{initial_humidity:.1f}%",
f"{adjusted_temp:.1f}°C",
f"{adjusted_humidity:.1f}%"))
# 安排下一次更新
self.after(self.update_interval, self.schedule_update)
if __name__ == "__main__":
app = ACApp()
app.mainloop()

Binary file not shown.
Loading…
Cancel
Save