From ed95659ef02dcce3db109e4cc1c2707f277678bf Mon Sep 17 00:00:00 2001 From: 123 <2070873540@qq.com> Date: Fri, 31 May 2024 11:37:11 +0800 Subject: [PATCH] 5 commit --- 智能家居系统/5.py | 111 +++++++++--- 智能家居系统/6.py | 134 ++++++++++++++ .../__pycache__/环境监测.cpython-311.pyc | Bin 0 -> 9574 bytes 智能家居系统/环境监测.py | 55 ++++-- 智能家居系统/空调调节.py | 171 ++++++++++++++++++ 5 files changed, 426 insertions(+), 45 deletions(-) create mode 100644 智能家居系统/6.py create mode 100644 智能家居系统/__pycache__/环境监测.cpython-311.pyc create mode 100644 智能家居系统/空调调节.py diff --git a/智能家居系统/5.py b/智能家居系统/5.py index 9915c70..386b941 100644 --- a/智能家居系统/5.py +++ b/智能家居系统/5.py @@ -1,54 +1,105 @@ +# -*- 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秒更新一次数据 - # 初始化数据 - self.temperature = 0 - self.humidity = 0 - self.light_intensity = 0 - self.record_count = 0 # 新增记录计数器 + # 设置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(root, columns=("序号", "参数", "值"), show="headings") + 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=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.pack(padx=10, pady=10) + 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) # 也可以根据需要调整按钮的位置 - # 模拟数据更新 - self.root.after(5000, self.update_data_and_display) # 每5秒更新一次数据 def simulate_data(self): - """Simulate environment data.""" - self.temperature = random.uniform(20, 30) # 温度范围20°C至30°C - self.humidity = random.uniform(30, 70) # 湿度范围30%至70% - self.light_intensity = random.randint(100, 1000) # 光照强度100至1000勒克斯 - self.record_count += 1 # 记录数加一 - - def update_table(self): - """Append new data to the table.""" - # 插入新数据,记录计数作为第一列 - self.treeview.insert("", tk.END, values=(self.record_count, "温度", f"{self.temperature:.2f} °C")) - self.treeview.insert("", tk.END, values=(self.record_count, "湿度", f"{self.humidity:.2f}%")) - self.treeview.insert("", tk.END, values=(self.record_count, "光照强度", f"{self.light_intensity} lux")) + 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): - """Update data and append to table display.""" self.simulate_data() - self.update_table() - # 递归调用以持续更新 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() diff --git a/智能家居系统/6.py b/智能家居系统/6.py new file mode 100644 index 0000000..ff3ff6a --- /dev/null +++ b/智能家居系统/6.py @@ -0,0 +1,134 @@ +import tkinter as tk +from tkinter import ttk +import random +import time + +class AirConditioner: + def __init__(self): + self.current_temperature = random.uniform(16, 30) + self.current_humidity = random.uniform(0, 100) + self.min_temperature = 16 + 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 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参数 + 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) # 使用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): + def __init__(self): + super().__init__() + self.title("空调自动调节系统") + self.geometry("800x600") # 调整窗口大小以适应内容 + + # 创建Treeview表格 + 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="调节后湿度") + self.treeview.column("编号", width=50, 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.column("调节后湿度", width=80, anchor=tk.CENTER) + self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10) + + self.aircon = AirConditioner() + self.line_number = 1 # 初始化行编号 + self.is_adjusting = True # 添加标志位,判断是否仍在调节过程中 + self.update_gui() # 先更新一次GUI + self.aircon.main_loop(self) # 传递self给main_loop以便使用after方法 + + self.treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) # 让Treeview自适应填充空间 + self.rowconfigure(0, weight=1) # 让树状视图所在的行填充额外空间 + self.columnconfigure(0, weight=1) # 让树状视图所在的列填充额外空间 + def update_gui(self): + if self.is_adjusting: # 只在调节过程中更新数据 + # 更新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 + else: # 调节完成后,添加最终状态 + if self.line_number == 1: # 如果还没有插入过数据,则插入第一行 + 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 + print("温度和湿度均在舒适范围内,停止调节。") + 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__": + app = ACApp() + app.mainloop() \ No newline at end of file diff --git a/智能家居系统/__pycache__/环境监测.cpython-311.pyc b/智能家居系统/__pycache__/环境监测.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..384622b0ad4b8b966dcd53f9a3909a230609c5d0 GIT binary patch literal 9574 zcmb_iYj6}-cJ7(!nd#B=Fal&DBq0eQ0fRvXVFL>U8zkOFSfGTpmd#{Px1@%7ak~eE z0*N+@Yb91TvSSCOEN7=SEGr7dVJqtmVR6=#U(Ua7RaY_9Ra9+NN?`p+l_a#A z+*bEYj|OnOzSBB=?)!D_ch0%3Uxq?u41~7bZ}y(6V3_~Hh!xm*=E)Q=*BF5jTydt` z1#fqpNw~Y+E==D)5cutH1zj&Y2mmy+XEO{;_cb(bY*VkjW0gP)t@?;k<*BFt`xZ5qbU<4k) z4U`o;K)nJB)Q2H>`k7NNGh2Slgg1)Qc_Z6cRJl; zPa68bW%j_|lb50EYs^L0MJ5VSGhAd&TP%~chGwTABe-rr`Yk)p#av{vh3(s=iqa5`vl0=pAf z!TXe4AI)W8nf)D^Dk%BroqwMB`Hvrc`0m3`e){l(+YjIVc;;6hJi2~&c6cen7{23D z;(#a(hI>;%L3Jt;wqCZuFWj_?LcQYppoDv}Zx4Nex7 zOgfs83|@#Su_zIHQbdrAU^<>sqUWWgkUDSpdZ}O;z8)%Ch9@>48{Sy2A`)X+CJhzE zD6Jh!3Q<9l)A85^!;_9H21k0{h>=)Aj<^k07UR7H7eU5dY-sqyW_Y!4KbgLu^rw<( zk~%H+C?_BO{oOBq{OQccznS^fTaW(bw~v1Nvy+AMZ%JP;xM)-YiHk-D>q<&ti!7S3_4qBjM5Ta5z_6H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$6ru#y=q&OCh~YUS zUXW3~8XAU72StX+A2ktFvHuG**%dRN&sW|#``OZa=j;SJ6F_rsJa$Tqcfq$r&!Chh z6p6h(aWO_nAC8Shn5Hfk>4!LxkkD&`077t765=9E23;+ZK#~D6KbhCe$sB@|!N%wB z3R;fxe*%GlKUh{h{_?~&wfUg=Xv+@i%MPJCUrou#{^31io*cjE>VYc4q&y4ojUBYwLHLluINYq0^ZuLm=4KO ze0aacCv-lc@(FC>;FW_Ther<&1H#ev#@a`Yj2;<=A9@%;^CC~<>UFMOwH~_29g!e@ zD@(=_Vl--$MWcz7kclJDN26ymvACH-P~_?Ttm!5l#3=QUsP06CMQ|le8N$m!b9M1N z6C`M3%2$C5*}pk=$h&!tu}N*%3;wB1ns_fEPxR_Jx@&E)^T5H^#Xd}yS^8t zXy@&iMGIyY5iEbN2d?gJOxS~@4M{taqN_E!yo#lt3}eKo|)(2KOj$x~X* zCcS3U(=O76L&KqkAcd9>T_F=_0oftJ48YrK)ayRZkQ0y&R?|~QZB)|Bmkfcc7r2B; z!8N2JrIPYsq{Ku@7sY*&5os)gDqC@Vg&J;Axt948<0XFy+2kUUOGxP9xQrZy(7gEn zHKrj!bdp^!I}oGyXy=+LI#(JNy&IBm4-dS6A%9ekWLrsLW9K;WCZe1!^kfJ z0Xz+cMqe4(I=XeJ{XtoMmetCd^|I!nwj9g-#t(H+I%n=;_s@2|L>CVcK9V^9P|SN0_GyWnu21+wTIoTSy*b+L!r^B_3A= mh^s|-hUJF`r#;J6&vMwOq4po`yS#6R{^mRkTMfx{xBd_L_6xiK literal 0 HcmV?d00001 diff --git a/智能家居系统/环境监测.py b/智能家居系统/环境监测.py index 5122fa1..c64b075 100644 --- a/智能家居系统/环境监测.py +++ b/智能家居系统/环境监测.py @@ -7,6 +7,7 @@ import time import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg + class EnvironmentMonitorApp: def __init__(self, root): self.root = root @@ -19,23 +20,31 @@ class EnvironmentMonitorApp: 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.treeview = ttk.Treeview(self.root, columns=("序号", "参数", "值"), show="headings") + # 调整窗口大小以适应更多数据 + 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=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.pack(padx=10, pady=10) - + 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) + self.plot_button.pack(pady=10) # 也可以根据需要调整按钮的位置 + def simulate_data(self): - self.temperature = random.uniform(20, 30) - self.humidity = random.uniform(30, 70) - self.light_intensity = random.randint(100, 1000) + self.temperature = random.uniform(-15, 40)#20-24 + self.humidity = random.uniform(0, 100)#40-60 + self.light_intensity = random.randint(100, 1000)#300-500 self.data_records.append({ "序号": len(self.data_records) + 1, "温度": self.temperature, @@ -47,20 +56,28 @@ class EnvironmentMonitorApp: 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")) - self.treeview.insert("", tk.END, values=(record["序号"], "湿度", f"{record['湿度']:.2f}%")) - self.treeview.insert("", tk.END, values=(record["序号"], "光照强度", f"{record['光照强度']} lux")) + 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('环境数据实时走势图') @@ -84,6 +101,14 @@ class EnvironmentMonitorApp: ax.grid(True) self.canvas.draw_idle() # 更新图表而不重新绘制整个画布 +class EnvironmentMonitor: + def __init__(self): + # 这里仅作为示例,实际应用中可能从传感器读取 + self.temperature = random.uniform(16, 30) + self.humidity = random.uniform(0, 100) + + def get_current_conditions(self): + return self.temperature, self.humidity def main(): root = tk.Tk() diff --git a/智能家居系统/空调调节.py b/智能家居系统/空调调节.py new file mode 100644 index 0000000..65f852f --- /dev/null +++ b/智能家居系统/空调调节.py @@ -0,0 +1,171 @@ +import tkinter as tk +from tkinter import ttk +import random +import time + +from 环境监测 import EnvironmentMonitor + + +def generate_initial_conditions(): + """ + 生成初始的温度和湿度条件,模拟从环境监测系统获取数据。 + """ + initial_temperature = random.uniform(16, 30) # 模拟从环境监测获得的温度 + initial_humidity = random.uniform(0, 100) # 模拟从环境监测获得的湿度 + return initial_temperature, initial_humidity +class AirConditioner: + def __init__(self, initial_temperature=None, initial_humidity=None): + if initial_temperature is not None: + self.current_temperature = initial_temperature + else: + self.current_temperature = random.uniform(16, 30) + + if initial_humidity is not None: + self.current_humidity = initial_humidity + else: + self.current_humidity = random.uniform(0, 100) + + def __init__(self, initial_temperature, initial_humidity): + self.current_temperature = initial_temperature + self.current_humidity = initial_humidity + self.current_temperature = random.uniform(16, 30) + self.current_humidity = random.uniform(0, 100) + self.min_temperature = 16 + 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 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参数 + 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) # 使用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): + def __init__(self): + super().__init__() + self.title("空调自动调节系统") + self.geometry("800x600") # 调整窗口大小以适应内容 + + # 从环境监测模拟获取初始温度和湿度 + self.initial_temperature, self.initial_humidity = generate_initial_conditions() + + # 初始化空调对象,传入初始温度和湿度 + self.aircon = AirConditioner( + initial_temperature=self.initial_temperature, + initial_humidity=self.initial_humidity + ) + + + + # 创建Treeview表格 + 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="调节后湿度") + self.treeview.column("编号", width=50, 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.column("调节后湿度", width=80, anchor=tk.CENTER) + self.treeview.grid(row=0, column=0, columnspan=4, padx=10, pady=10) + + self.aircon = AirConditioner() + self.line_number = 1 # 初始化行编号 + self.is_adjusting = True # 添加标志位,判断是否仍在调节过程中 + self.update_gui() # 先更新一次GUI + self.aircon.main_loop(self) # 传递self给main_loop以便使用after方法 + + self.treeview.pack(expand=True, fill=tk.BOTH, padx=10, pady=10) # 让Treeview自适应填充空间 + self.rowconfigure(0, weight=1) # 让树状视图所在的行填充额外空间 + self.columnconfigure(0, weight=1) # 让树状视图所在的列填充额外空间 + def update_gui(self): + if self.is_adjusting: # 只在调节过程中更新数据 + # 更新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 + else: # 调节完成后,添加最终状态 + if self.line_number == 1: # 如果还没有插入过数据,则插入第一行 + 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 + print("温度和湿度均在舒适范围内,停止调节。") + 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__": + env_monitor = EnvironmentMonitor() # 创建环境监测实例 + current_temp, current_humidity = env_monitor.get_current_conditions() # 获取当前环境温湿度 + + app = ACApp(current_temp, current_humidity) # 传入实际的温湿度值初始化ACApp + app.mainloop() \ No newline at end of file