【发布时间】:2020-07-29 11:20:13
【问题描述】:
我正在尝试将 psutil.cpu_percent() 绘制为 Tkinter 中的实时图表,但我无法让它工作。 我的主要问题是让 cpu_percent 有一个“历史”,而不仅仅是每秒绘制一个点。
另外,我不希望使用 cpu_percent() 结果创建一个不断扩展的数据框,因为如果不断运行我的脚本,这可能是一个问题。 - 所以我正在寻找可能创建某种正在运行的数据帧循环来清除最旧的条目,或者类似的东西。
我对哪种解决方案最好并不挑剔,只要 tkinter 窗口以一定的固定间隔显示带有 cpu 信息的实时运行图。
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import Toplevel
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showinfo, showwarning, askquestion
from tkinter import OptionMenu
from tkinter import StringVar
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from matplotlib import style
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from psutil import cpu_percent
from sklearn.metrics import silhouette_score
from sklearn.cluster import KMeans
import sklearn.cluster as cluster
import scipy.spatial.distance as sdist
from sklearn.ensemble import IsolationForest
import pandas as pd
import numpy as np
import seaborn as sn
from datetime import datetime
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
RANDOM_STATE = 42 #used to help randomly select the data points
low_memory=False
LARGE_FONT= ("Verdana", 12)
style.use("ggplot")
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
LARGE_FONT= ("Verdana", 12)
style.use("ggplot")
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
def animate(i):
cpu_measure = cpu_percent()
dateTimeObj = datetime.now()
cpu_time = dateTimeObj.strftime("%H:%M:%S")
a.clear()
a.plot_date(cpu_time, cpu_measure, label='CPU Usage')
a.legend(bbox_to_anchor=(0, 1.02, 1, .102), loc=3,
ncol=2, borderaxespad=0)
title = "Graph"
a.set_title(title)
class Analyticsapp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
#tk.Tk.iconbitmap(self, default="iconimage_kmeans.ico") #Icon for program
tk.Tk.wm_title(self, "Advanched analytics")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, GraphPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text=
"Advanched analytics", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button3 = ttk.Button(self, text="Live Plot",
command=lambda: controller.show_frame(GraphPage))
button3.pack(fill='x')
class GraphPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Example of Live Plotting", font=LARGE_FONT)
label.pack(pady=10,padx=10)
canvas = FigureCanvasTkAgg(f, self)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
button1 = ttk.Button(self, text="Back",
command=lambda: controller.show_frame(StartPage))
button1.pack()
app = Analyticsapp()
app.geometry('500x400')
ani = animation.FuncAnimation(f, animate, interval=1000)
app.mainloop()
【问题讨论】:
-
能否将导入语句添加到您的代码中?
-
现在添加了完整的可用代码。感谢您的建议。不知道为什么我没有从一开始就这样做。
标签: python function class matplotlib tkinter