用Python写一段tk图形化代码。可以实时显示C盘读写活动、D盘读写活动、网络活动(注意异常: TypeError get_disk_io() takes 0 positional arguments but 1 was given)
时间: 2023-06-27 20:01:48 浏览: 47
以下是一个简单的示例代码,使用psutil模块获取磁盘和网络读写活动,并用tkinter创建GUI应用程序来实时显示它们。
```python
import psutil
import tkinter as tk
def get_disk_io():
disk_io = psutil.disk_io_counters()
return disk_io.read_bytes, disk_io.write_bytes
def get_net_io():
net_io = psutil.net_io_counters()
return net_io.bytes_recv, net_io.bytes_sent
root = tk.Tk()
root.title("实时监控")
# 创建标签
label_c = tk.Label(root, text="C盘读写活动: ")
label_c.pack()
label_d = tk.Label(root, text="D盘读写活动: ")
label_d.pack()
label_net = tk.Label(root, text="网络活动: ")
label_net.pack()
# 更新标签内容
def update_labels():
try:
c_read, c_write = get_disk_io()
d_read, d_write = get_disk_io()
net_recv, net_sent = get_net_io()
label_c.config(text=f"C盘读: {c_read/1024/1024:.2f} MB/s 写: {c_write/1024/1024:.2f} MB/s")
label_d.config(text=f"D盘读: {d_read/1024/1024:.2f} MB/s 写: {d_write/1024/1024:.2f} MB/s")
label_net.config(text=f"接收: {net_recv/1024/1024:.2f} MB/s 发送: {net_sent/1024/1024:.2f} MB/s")
except TypeError:
pass
root.after(1000, update_labels)
update_labels()
root.mainloop()
```
该代码创建了一个简单的GUI应用程序,包括三个标签,用于显示C盘、D盘和网络读写速度。`update_labels`函数使用`after`方法定期更新标签内容(每秒一次)。注意到`get_disk_io`和`get_net_io`函数需要返回磁盘和网络读写活动的字节数,因此我们需要使用`psutil`模块来获取这些信息。由于`disk_io_counters`和`net_io_counters`函数返回的对象是命名元组,因此我们可以使用`obj.attribute`的形式来获取它们的属性,例如`disk_io.read_bytes`返回C盘的读字节数。最后,我们在`update_labels`函数中捕获`TypeError`异常,以防止由于错误的参数传递而引发错误。