You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
2.2 KiB
60 lines
2.2 KiB
9 months ago
|
import tkinter as tk
|
||
|
from tkinter import ttk
|
||
|
import random
|
||
|
import time
|
||
|
|
||
|
|
||
|
class EnvironmentMonitorApp:
|
||
|
def __init__(self, root):
|
||
|
self.root = root
|
||
|
self.root.title("环境监测数据展示")
|
||
|
|
||
|
# 初始化数据
|
||
|
self.temperature = 0
|
||
|
self.humidity = 0
|
||
|
self.light_intensity = 0
|
||
|
self.record_count = 0 # 新增记录计数器
|
||
|
|
||
|
# 创建表格
|
||
|
self.treeview = ttk.Treeview(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.heading("序号", text="序号")
|
||
|
self.treeview.heading("参数", text="参数")
|
||
|
self.treeview.heading("值", text="值")
|
||
|
self.treeview.pack(padx=10, 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"))
|
||
|
|
||
|
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 main():
|
||
|
root = tk.Tk()
|
||
|
app = EnvironmentMonitorApp(root)
|
||
|
root.mainloop()
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|