# -*- coding:utf-8 -*-
"""
通过这个小程序,来学习Tk及psutil
"""
import tkinter as Tk
import psutil
class Tag(Tk.Frame):
def __init__(self, root, label, value, **args):
super(Tag, self).__init__(root, **args)
self._label = Tk.Label(self, text=label)
self._value = Tk.StringVar()
self._value.set(str(value))
self._entry = Tk.Entry(self, textvariable=self._value)
# pack
self._label.pack(side=Tk.LEFT)
self._entry.pack(side=Tk.RIGHT)
def set(self, value):
self._value.set(value)
def get(self):
return self._value.get()
class Cpu(Tk.Frame):
def __init__(self, root=None, **args):
super(Cpu, self).__init__(root, **args)
self.initUi()
def initUi(self):
self._title = Tk.Label(self, text='CPU')
self._cpu = []
for i in range(psutil.cpu_count()):
self._cpu.append(Tag(self, 'cpu.{}'.format(i), "0%"))
# pack
self._title.pack()
for i in self._cpu:
i.pack()
def change(self):
for i, v in enumerate(psutil.cpu_percent(interval=1, percpu=True)):
self._cpu[i].set("{}%".format(v))
class VirtualMemory(Tk.Frame):
K = 1024
M = K * K
def __init__(self, root=None, **args):
super(VirtualMemory, self).__init__(root, **args)
self.initUi()
def initUi(self):
self._title = Tk.Label(self, text='内存')
self._percent = Tag(self, '使用比例', "0%")
self._used = Tag(self, '已用', 0)
self._free = Tag(self, '剩余', 0)
# pack
self._title.pack()
self._percent.pack()
self._used.pack()
self._free.pack()
def change(self):
data = psutil.virtual_memory()
self._percent.set("{}%".format(data.percent))
self._used.set("{}MB".format(data.used//self.M))
self._free.set("{}MB".format(data.free//self.M))
class NetCounter(Tk.Frame):
"""
显示单个网络设备的流量
"""
def __init__(self, master=None, eth='eth0', **args):
super(NetCounter, self).__init__(master, **args)
self.__eth = eth
self.initUi()
self.__data = psutil.net_io_counters(pernic=True)[eth]
def initUi(self):
self.label = Tk.Label(self, text='{}'.format(self.__eth))
self.up = Tag(self, '上传速度', '0/k')
self.down = Tag(self, '下载速度', '0/k')
# pack
self.label.pack()
self.up.pack()
self.down.pack()
def change(self):
now = psutil.net_io_counters(pernic=True)[self.__eth]
self.up.set("%d/k" %
((now.bytes_sent - self.__data.bytes_sent) // 1024))
self.down.set("%d/k" %
((now.bytes_recv - self.__data.bytes_recv) // 1024))
self.__data = now
class Application(Tk.Frame):
def __init__(self, top=None):
super(Application, self).__init__(top)
self.initUi()
self.after(1000, self.loop)
def initUi(self):
self._net = []
l = list(psutil.net_if_stats().keys())
l.sort()
for item in l:
n = NetCounter(self, eth=item, relief=Tk.RAISED,
borderwidth=1)
self._net.append(n)
self._vm = VirtualMemory(self, relief=Tk.RAISED)
self._cpu = Cpu(self, relief=Tk.RAISED)
# pack
for i in self._net:
i.pack()
self._vm.pack()
self._cpu.pack()
def loop(self):
for i in self._net:
i.change()
self._vm.change()
self._cpu.change()
self.after(1000, self.loop)
def main():
root = Tk.Tk()
root.title('系统监控小程序')
app = Application(root)
app.pack(fill=Tk.BOTH, expand=1)
app.mainloop()
if __name__ == '__main__':
main()