python/tk 学习总结

tk 学习总结

布局

  1. grid 按行列排局。
  2. pack 在原有基础上,拼接。
    • 从哪个方向拼接, 左右上下。
  3. 当部件大小小于分配给它空间时表现。

tk 注意点

  1. 调试布局表现时,把背景色打开,更能调试出问题。
  2. grid, pack不能混合使用(个人经验)。
  3. 调用after来实现定时更新。

tk 实践经验

  1. 使用类的方式,写tk代码会更少。

tk 实例

截图

# -*- 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()
Loading Disqus comments...
Table of Contents