main
123 6 months ago
parent 905b38c36a
commit a8838866e5

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

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

@ -5,129 +5,62 @@ import time
class AirConditioner: class AirConditioner:
def __init__(self): def __init__(self):
self.current_temperature = random.uniform(16, 30) self.comfortable_temperature_range = (20, 24) # 添加舒适温度范围
self.current_humidity = random.uniform(0, 100) self.comfortable_humidity_range = (40, 60) # 添加舒适湿度范围
self.min_temperature = 16 self.reset_conditions()
self.max_temperature = 30
self.min_humidity = 0
self.max_humidity = 100
self.comfortable_temperature_range = (20, 24) # 舒适温度范围
self.comfortable_humidity_range = (40, 60) # 舒适湿度范围
def adjust_temperature(self):
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[
1]:
if self.current_temperature < self.comfortable_temperature_range[0]:
self.current_temperature += 1
elif self.current_temperature > self.comfortable_temperature_range[1]:
self.current_temperature -= 1 def reset_conditions(self):
self.current_temperature = random.uniform(-12, 42)
def adjust_humidity(self): self.current_humidity = random.uniform(0, 100)
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
if self.current_humidity < self.comfortable_humidity_range[0]:
self.current_humidity += 5
elif self.current_humidity > self.comfortable_humidity_range[1]:
self.current_humidity -= 5
def display_status(self):
print(f"当前温度: {self.current_temperature:.1f}°C, 当前湿度: {self.current_humidity:.1f}%")
def main_loop(self, root): # 接受root参数 def adjust(self):
self.reset_conditions() # 获取新的初始温度和湿度
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]: if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]:
self.adjust_temperature() self.current_temperature = random.uniform(*self.comfortable_temperature_range)
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]: if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
self.adjust_humidity() self.current_humidity = random.uniform(*self.comfortable_humidity_range)
return self.current_temperature, self.current_humidity # 返回调节后的温度和湿度
if not (
self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]
and
self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]
):
self.display_status()
root.after(1000, self.main_loop, root) # 使用after而非sleep
else:
print("温度和湿度均在舒适范围内,停止调节。")
print(f"温度: {self.current_temperature:.1f}°C, 湿度: {self.current_humidity:.1f}%")
# 可能需要在这里调用一次update_gui以最终更新GUI显示结果
# self.app.update_gui_final() 如果在ACApp类中实现了这个方法来显示最终状态
class ACApp(tk.Tk): class ACApp(tk.Tk):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.title("空调自动调节系统") self.title("空调自动调节系统")
self.geometry("800x600") # 调整窗口大小以适应内容 self.geometry("800x600")
# 创建Treeview表格 self.treeview = ttk.Treeview(self,
self.treeview = ttk.Treeview(self, columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"), columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"),
show="headings") show="headings")
self.treeview.heading("编号", text="编号") self.treeview.heading("编号", text="编号")
self.treeview.heading("初始温度", text="初始温度") self.treeview.heading("初始温度", text="初始温度")
self.treeview.heading("初始湿度", text="初始湿度") self.treeview.heading("初始湿度", text="初始湿度")
self.treeview.heading("调节后温度", text="调节后温度") self.treeview.heading("调节后温度", text="调节后温度")
self.treeview.heading("调节后湿度", text="调节后湿度") self.treeview.heading("调节后湿度", text="调节后湿度")
self.treeview.column("编号", width=50, anchor=tk.CENTER) for col in self.treeview['columns']:
self.treeview.column("初始温度", width=80, anchor=tk.CENTER) self.treeview.column(col, width=80, anchor=tk.CENTER)
self.treeview.column("初始湿度", width=80, anchor=tk.CENTER)
self.treeview.column("调节后温度", width=80, anchor=tk.CENTER)
self.treeview.column("调节后湿度", width=80, anchor=tk.CENTER)
self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10) self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
self.aircon = AirConditioner() self.aircon = AirConditioner()
self.line_number = 1 # 初始化行编号 self.line_number = 0
self.is_adjusting = True # 添加标志位,判断是否仍在调节过程中 self.is_adjusted = False
self.update_gui() # 先更新一次GUI self.update_interval = 5000 # 每5秒更新一次
self.aircon.main_loop(self) # 传递self给main_loop以便使用after方法 self.schedule_update() # 安排首次更新
self.treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) # 让Treeview自适应填充空间 self.treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.rowconfigure(0, weight=1) # 让树状视图所在的行填充额外空间 self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1) # 让树状视图所在的列填充额外空间 self.columnconfigure(0, weight=1)
def update_gui(self):
if self.is_adjusting: # 只在调节过程中更新数据 def schedule_update(self):
# 更新Treeview中的数据这里假设初始数据就是当前数据实际应用中可能需要记录调节前的实际初始值 """计划下一次更新"""
self.treeview.insert("", tk.END, values=(self.line_number,
f"{self.aircon.current_temperature:.1f}°C",
f"{self.aircon.current_humidity:.1f}%",
f"{self.aircon.current_temperature:.1f}°C",
f"{self.aircon.current_humidity:.1f}%"))
self.line_number += 1 self.line_number += 1
else: # 调节完成后,添加最终状态 initial_temp, initial_humidity = self.aircon.current_temperature, self.aircon.current_humidity
if self.line_number == 1: # 如果还没有插入过数据,则插入第一行 adjusted_temp, adjusted_humidity = self.aircon.adjust()
self.treeview.insert("", tk.END, values=(self.line_number, self.treeview.insert("", tk.END, values=(self.line_number,
f"{self.aircon.current_temperature:.1f}°C", f"{initial_temp:.1f}°C",
f"{self.aircon.current_humidity:.1f}%", f"{initial_humidity:.1f}%",
f"{self.aircon.current_temperature:.1f}°C", f"{adjusted_temp:.1f}°C",
f"{self.aircon.current_humidity:.1f}%")) f"{adjusted_humidity:.1f}%"))
self.line_number += 1 # 安排下一次更新
print("温度和湿度均在舒适范围内,停止调节。") self.after(self.update_interval, self.schedule_update)
print(f"温度: {self.current_temperature:.1f}°C, 湿度: {self.current_humidity:.1f}%")
self.is_adjusting = False # 设置标志位为False停止调节后的数据更新
def main_loop(self, root):
if self.is_adjusting:
if not self.comfortable_temperature_range[0] <= self.current_temperature <= \
self.comfortable_temperature_range[1]:
self.adjust_temperature()
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
self.adjust_humidity()
if not (
self.comfortable_temperature_range[0] <= self.current_temperature <=
self.comfortable_temperature_range[1]
and
self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]
):
self.display_status()
root.after(1000, self.main_loop, root)
else:
self.is_adjusting = False # 温湿度达到舒适范围后设置标志位为False
else:
self.update_gui() # 最后调用一次update_gui以显示最终状态
if __name__ == "__main__": if __name__ == "__main__":
app = ACApp() app = ACApp()

@ -0,0 +1,41 @@
import tkinter as tk
from tkinter import messagebox
from ZYM import a
def login_check(root, username_var, password_var):
name = username_var.get()
pwd = password_var.get()
if name == '123' and pwd == '123':
messagebox.showinfo(title='恭喜', message='登录成功')
xiaohui()
# MainPage(root) # 如果需要,取消注释此行并确保已正确导入主页面模块
else:
messagebox.showinfo(title='错误', message='账户或密码错误')
def main():
global root
root = tk.Tk()
root.title('智能家居系统-登录界面')
root.geometry("300x180")
username_var = tk.StringVar()
password_var = tk.StringVar()
tk.Label(root).grid(row=0, column=0)
tk.Label(root, text='账户').grid(row=1,column=0)
tk.Entry(root, textvariable=username_var).grid(row=1, column=1)
tk.Label(root, text='密码').grid(row=2, column=0)
tk.Entry(root, textvariable=password_var).grid(row=2, column=1, pady=10)
tk.Button(root, text='登录', command=lambda: login_check(root, username_var, password_var)).grid(row=3, column=0, pady=10)
tk.Button(root, text='退出', command=root.quit).grid(row=3, column=1, pady=10, sticky=tk.E)
root.mainloop()
def xiaohui():
root.destroy()
a()
if __name__ == '__main__':
main()

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

@ -0,0 +1,256 @@
import tkinter as tk
from tkinter import ttk
import pymysql
from tkinter import messagebox
# 初始化数据库连接
def init_db_connection():
global conn, cursor
conn = pymysql.connect(host='localhost', user='root', password='LH20021212', db='智能家居系统', charset='utf8mb4')
cursor = conn.cursor()
# 创建主界面
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
root = tk.Tk()
root.title("智能家居系统-家居信息")
root.geometry('1000x700')
init_db_connection()
create_widgets()
root.protocol("WM_DELETE_WINDOW", close_conn)
root.mainloop()
# 创建界面组件
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
# 表格和滚动条
frame = tk.Frame(root)
frame.pack(fill=tk.BOTH, expand=True)
scrollbar_y = tk.Scrollbar(frame, orient=tk.VERTICAL)
scrollbar_x = tk.Scrollbar(frame, orient=tk.HORIZONTAL)
tree = ttk.Treeview(frame, columns=("ID", "名称", "颜色", "品牌", "价格", "生产日期"),
yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set)
tree.heading("#0", text="")
tree.heading("ID", text="ID")
tree.heading("名称", text="名称")
tree.heading("颜色", text="颜色")
tree.heading("品牌", text="品牌")
tree.heading("价格", text="价格")
tree.heading("生产日期", text="生产日期")
tree.column("#0", width=0, stretch=tk.NO)
tree.column("ID", anchor=tk.CENTER, width=50)
tree.column("名称", anchor=tk.CENTER, width=100)
tree.column("颜色", anchor=tk.CENTER, width=100)
tree.column("品牌", anchor=tk.CENTER, width=100)
tree.column("价格", anchor=tk.CENTER, width=100)
tree.column("生产日期", anchor=tk.CENTER, width=100)
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar_y.config(command=tree.yview)
scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
scrollbar_x.config(command=tree.xview)
scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
# 按钮区域
button_frame = tk.Frame(root)
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=delete_selected_jiaju).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="修改选中", command=update_selected_jiaju_popup).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)
# 查询条件输入框区域
query_frame = tk.Frame(root)
query_frame.pack(pady=(10, 0))
tk.Label(query_frame, text="名称:").pack(side=tk.LEFT)
entry_name_query = tk.Entry(query_frame)
entry_name_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="颜色:").pack(side=tk.LEFT)
entry_color_query = tk.Entry(query_frame)
entry_color_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="品牌:").pack(side=tk.LEFT)
entry_brand_query = tk.Entry(query_frame)
entry_brand_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="价格:").pack(side=tk.LEFT)
entry_price_query = tk.Entry(query_frame)
entry_price_query.pack(side=tk.LEFT, padx=(5, 0))
tk.Label(query_frame, text="生产日期:").pack(side=tk.LEFT)
entry_production_date_query = tk.Entry(query_frame)
entry_production_date_query.pack(side=tk.LEFT)
tk.Button(query_frame, text="查询", command=query_jiaju_condition).pack(side=tk.LEFT, padx=10)
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 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:
cursor.execute(sql)
conn.commit()
messagebox.showinfo("成功", "家居信息录入成功!")
add_window.destroy()
query_all_jiaju()
except Exception as e:
messagebox.showerror("错误", f"录入失败: {e}")
add_window = tk.Toplevel(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():
selected_items = tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请先选择要修改的家居项!")
return
item = selected_items[0]
item_values = 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:
cursor.execute(sql)
conn.commit()
messagebox.showinfo("成功", "家居信息已更新!")
update_window.destroy()
query_all_jiaju()
except Exception as e:
messagebox.showerror("错误", f"更新失败: {e}")
update_window = tk.Toplevel(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():
name_cond = entry_name_query.get().strip()
color_cond = entry_color_query.get().strip()
brand_cond = entry_brand_query.get().strip()
price_cond = entry_price_query.get().strip()
production_date_cond = 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:
cursor.execute(sql)
rows = cursor.fetchall()
tree.delete(*tree.get_children())
for row in rows:
tree.insert('', tk.END, values=row)
except Exception as e:
messagebox.showerror("错误", f"查询失败: {e}")
conn.rollback()
# 关闭数据库连接
def close_conn():
cursor.close()
conn.close()
root.destroy()
if __name__ == '__main__':
create_main_window()

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

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

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

@ -3,7 +3,7 @@ import tkinter as tk
import tkinter.messagebox import tkinter.messagebox
from 主页面 import MainPage from 主页面 import MainPage
#from 家居信息 import JiaJuPage
class LoginPage: class LoginPage:

@ -5,141 +5,62 @@ import time
class AirConditioner: class AirConditioner:
def __init__(self): def __init__(self):
self.current_temperature = random.uniform(16, 30) self.comfortable_temperature_range = (20, 24) # 添加舒适温度范围
self.current_humidity = random.uniform(0, 100) self.comfortable_humidity_range = (40, 60) # 添加舒适湿度范围
self.min_temperature = 16 self.reset_conditions()
self.max_temperature = 30
self.min_humidity = 0
self.max_humidity = 100
self.comfortable_temperature_range = (20, 24) # 舒适温度范围
self.comfortable_humidity_range = (40, 60) # 舒适湿度范围
self.environment_variation = True # 控制环境波动开关
def simulate_environment_change(self):
if self.environment_variation:
# 模拟温度和湿度的随机微小波动
self.current_temperature += random.uniform(-1, 1)
self.current_humidity += random.uniform(-5, 5)
# 确保波动后的值仍在合理范围内
self.current_temperature = max(min(self.current_temperature, self.max_temperature), self.min_temperature)
self.current_humidity = max(min(self.current_humidity, self.max_humidity), self.min_humidity)
def adjust_temperature(self):
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[
1]:
if self.current_temperature < self.comfortable_temperature_range[0]:
self.current_temperature += 1 def reset_conditions(self):
elif self.current_temperature > self.comfortable_temperature_range[1]: self.current_temperature = random.uniform(-12, 42)
self.current_humidity = random.uniform(0, 100)
self.current_temperature -= 1
def adjust_humidity(self):
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
if self.current_humidity < self.comfortable_humidity_range[0]:
self.current_humidity += 5
elif self.current_humidity > self.comfortable_humidity_range[1]:
self.current_humidity -= 5
def display_status(self):
print(f"当前温度: {self.current_temperature:.1f}°C, 当前湿度: {self.current_humidity:.1f}%")
def main_loop(self, root): # 接受root参数 def adjust(self):
self.reset_conditions() # 获取新的初始温度和湿度
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]: if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]:
self.adjust_temperature() self.current_temperature = random.uniform(*self.comfortable_temperature_range)
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]: if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
self.adjust_humidity() self.current_humidity = random.uniform(*self.comfortable_humidity_range)
return self.current_temperature, self.current_humidity # 返回调节后的温度和湿度
if not (
self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]
and
self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]
):
self.display_status()
root.after(1000, self.main_loop, root) # 使用after而非sleep
else:
print("温度和湿度均在舒适范围内,停止调节。")
print(f"温度: {self.current_temperature:.1f}°C, 湿度: {self.current_humidity:.1f}%")
# 可能需要在这里调用一次update_gui以最终更新GUI显示结果
# self.app.update_gui_final() 如果在ACApp类中实现了这个方法来显示最终状态
class ACApp(tk.Tk): class ACApp(tk.Tk):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.title("空调自动调节系统") self.title("空调自动调节系统")
self.geometry("800x600") # 调整窗口大小以适应内容 self.geometry("800x600")
# 创建Treeview表格 self.treeview = ttk.Treeview(self,
self.treeview = ttk.Treeview(self, columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"), columns=("编号", "初始温度", "初始湿度", "调节后温度", "调节后湿度"),
show="headings") show="headings")
self.treeview.heading("编号", text="编号") self.treeview.heading("编号", text="编号")
self.treeview.heading("初始温度", text="初始温度") self.treeview.heading("初始温度", text="初始温度")
self.treeview.heading("初始湿度", text="初始湿度") self.treeview.heading("初始湿度", text="初始湿度")
self.treeview.heading("调节后温度", text="调节后温度") self.treeview.heading("调节后温度", text="调节后温度")
self.treeview.heading("调节后湿度", text="调节后湿度") self.treeview.heading("调节后湿度", text="调节后湿度")
self.treeview.column("编号", width=50, anchor=tk.CENTER) for col in self.treeview['columns']:
self.treeview.column("初始温度", width=80, anchor=tk.CENTER) self.treeview.column(col, width=80, anchor=tk.CENTER)
self.treeview.column("初始湿度", width=80, anchor=tk.CENTER)
self.treeview.column("调节后温度", width=80, anchor=tk.CENTER)
self.treeview.column("调节后湿度", width=80, anchor=tk.CENTER)
self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10) self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
self.aircon = AirConditioner() self.aircon = AirConditioner()
self.line_number = 1 # 初始化行编号 self.line_number = 0
self.is_adjusting = True # 添加标志位,判断是否仍在调节过程中 self.is_adjusted = False
self.update_gui() # 先更新一次GUI self.update_interval = 5000 # 每5秒更新一次
self.aircon.main_loop(self) # 传递self给main_loop以便使用after方法 self.schedule_update() # 安排首次更新
self.treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) # 让Treeview自适应填充空间 self.treeview.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.rowconfigure(0, weight=1) # 让树状视图所在的行填充额外空间 self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1) # 让树状视图所在的列填充额外空间 self.columnconfigure(0, weight=1)
def update_gui(self):
if self.is_adjusting: # 只在调节过程中更新数据 def schedule_update(self):
# 更新Treeview中的数据这里假设初始数据就是当前数据实际应用中可能需要记录调节前的实际初始值 """计划下一次更新"""
self.treeview.insert("", tk.END, values=(self.line_number,
f"{self.aircon.current_temperature:.1f}°C",
f"{self.aircon.current_humidity:.1f}%",
f"{self.aircon.current_temperature:.1f}°C",
f"{self.aircon.current_humidity:.1f}%"))
self.line_number += 1 self.line_number += 1
else: # 调节完成后,添加最终状态 initial_temp, initial_humidity = self.aircon.current_temperature, self.aircon.current_humidity
if self.line_number == 1: # 如果还没有插入过数据,则插入第一行 adjusted_temp, adjusted_humidity = self.aircon.adjust()
self.treeview.insert("", tk.END, values=(self.line_number, self.treeview.insert("", tk.END, values=(self.line_number,
f"{self.aircon.current_temperature:.1f}°C", f"{initial_temp:.1f}°C",
f"{self.aircon.current_humidity:.1f}%", f"{initial_humidity:.1f}%",
f"{self.aircon.current_temperature:.1f}°C", f"{adjusted_temp:.1f}°C",
f"{self.aircon.current_humidity:.1f}%")) f"{adjusted_humidity:.1f}%"))
self.line_number += 1 # 安排下一次更新
print("温度和湿度均在舒适范围内,停止调节。") self.after(self.update_interval, self.schedule_update)
print(f"温度: {self.current_temperature:.1f}°C, 湿度: {self.current_humidity:.1f}%")
self.is_adjusting = False # 设置标志位为False停止调节后的数据更新
def main_loop(self):
if self.is_adjusting:
# 新增模拟环境变化
self.aircon.simulate_environment_change()
if not self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]:
self.adjust_temperature()
if not self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]:
self.adjust_humidity()
if not (
self.comfortable_temperature_range[0] <= self.current_temperature <= self.comfortable_temperature_range[1]
and
self.comfortable_humidity_range[0] <= self.current_humidity <= self.comfortable_humidity_range[1]
):
self.display_status()
self.after(1000, self.main_loop) # 继续循环
else:
self.is_adjusting = False
self.update_gui_final() # 假设这里调用最后的更新GUI方法
else:
pass # 已经调整完毕,无需操作
if __name__ == "__main__": if __name__ == "__main__":
app = ACApp() app = ACApp()

Binary file not shown.
Loading…
Cancel
Save