Table of Contents
1. Project preparation" >1. Project preparation
2. Write the menu bar " >2. Write the menu bar
1) First we need to create a main menu and then load each submenu into it: " >1) First we need to create a main menu and then load each submenu into it:
2 ) Create each submenu: " >2 ) Create each submenu:
3) Add the menu to the main interface configuration" >3) Add the menu to the main interface configuration
3. Functions in the interface" >3. Functions in the interface
1)编写按钮" >1)编写按钮
2)编写多行文本框
" >2)编写多行文本框
3)编写函数实现简单功能
" >3)编写函数实现简单功能
4)编写下面的进程数,CPU使用率,物理内存" >4)编写下面的进程数,CPU使用率,物理内存
5)给多行文本框添加滚动条
" >5)给多行文本框添加滚动条
6)添加状态栏文本标签
" >6)添加状态栏文本标签
7)实现状态栏标签功能" >7)实现状态栏标签功能
8)功能编写" >8)功能编写
1.编写应用程序选项" >1.编写应用程序选项
2.编写进程选项" >2.编写进程选项
3.编写服务选项" >3.编写服务选项
4.编写性能选项" >4.编写性能选项
5.编写联网选项" >5.编写联网选项
6.编写用户选项" >6.编写用户选项
3. Summary" >3. Summary
Home Backend Development Python Tutorial Teach you step by step how to imitate a task manager using Python

Teach you step by step how to imitate a task manager using Python

Jul 25, 2023 pm 03:26 PM
python

I believe everyone is familiar with the Task Manager. Ctrl Alt Del can open it, then click to start the Task Manager, or right-click the taskbar-Start Task Manager to start the Task Manager. Start After that, the interface is as follows:

Teach you step by step how to imitate a task manager using Python

It can be seen that it lists some important parameters, such as the number of processes, CPU usage, physical memory, next Let’s list them one by one.


1. Project preparation

Editor: sublime text 3

Module: psutil tkinter


## 2. Implementation steps

1. Write the main interface

To implement the task manager, first we write an interface. Here we use tkinter to write an interface. :

Teach you step by step how to imitate a task manager using Python

2. Write the menu bar

Let’s implement its menu bar first. The Menu module of tkinter is used here. I don’t know if you have any impression, so let’s get started. .

1) First we need to create a main menu and then load each submenu into it:

m=t.Menu(root)
Copy after login

2 ) Create each submenu:

#文件菜单
file=t.Menu(m,tearoff=False) 
m.add_cascade(label='文件', menu=file)
file.add_command(label='新建任务',accelerator='(N)')
file.add_command(label='退出任务栏管理器',command=root.quit,accelerator='(x)')




#选项菜单
ii=t.IntVar()
ii.set(1)
o=t.Menu(m,tearoff=False)
m.add_cascade(label='选项',menu=o)
o.add_radiobutton(label='前端显示',variable=ii, value=0)
o.add_radiobutton(label='使用时最小化',variable=ii, value=1)
o.add_radiobutton(label='最小化时隐藏',variable=ii, value=2)




#查看菜单
v=t.Menu(m,tearoff=False)
m.add_cascade(label='查看',menu=v)
v.add_command(label='立即刷新')
#二级菜单
iv=t.IntVar()
iv.set(1)
s=t.Menu(v,tearoff=False)
v.add_cascade(label='更新速度',menu=s)
s.add_radiobutton(label='高',variable=iv, value=0)
s.add_radiobutton(label='普通',variable=iv, value=1)
s.add_radiobutton(label='低',variable=iv, value=2)
s.add_radiobutton(label='暂停',variable=iv, value=3)
v.add_command(label='选项列')




#帮助菜单
h=t.Menu(m,tearoff=False)
m.add_cascade(label='帮助',menu=h)
h.add_command(label='任务管理器帮助主体')
h.add_command(label='关于任务管理器')
Copy after login

3) Add the menu to the main interface configuration

root.configure(menu=m)
Copy after login

As you can see from the final result picture, it is basically similar to the task manager.

Teach you step by step how to imitate a task manager using Python

3. Functions in the interface

After the interface is written, we should add it to the interface Component, we can see from the picture of the task manager that it has a button to switch task windows:

1)编写按钮

b1=t.Button(root,text='应用程序',command=yy)
b2=t.Button(root,text='进程',command=jc)
b3=t.Button(root,text='服务',command=fw)
b4=t.Button(root,text='性能',command=xn)
b5=t.Button(root,text='联网',command=lw)
b6=t.Button(root,text='用户',command=yh)


#定位
b1.place(x=10,y=15,height=20,width=60)
b2.place(x=70,y=15,height=20,width=60)
b3.place(x=130,y=15,height=20,width=60)
b4.place(x=190,y=15,height=20,width=60)
b5.place(x=250,y=15,height=20,width=60)
b6.place(x=310,y=15,height=20,width=60)
Copy after login

2)编写多行文本框

text=t.Text(root,width=100,height=40)
text.place(x=10,y=36)
Copy after login

3)编写函数实现简单功能

def yy():
    text.delete(1.0,'end')
    text.insert('insert','yy')
def jc():
    text.delete(1.0,'end')
    text.insert('insert','jc')
def fw():
    text.delete(1.0,'end')
    text.insert('insert','fw')
def xn():
    text.delete(1.0,'end')
    text.insert('insert','xn')
def lw():
    text.delete(1.0,'end')
    text.insert('insert','lw')
def yh():
    text.delete(1.0,'end')
    text.insert('insert','yh')
Copy after login

这样就实现了不同按钮之间切换不同的界面。

4)编写下面的进程数,CPU使用率,物理内存

我们使用标签来放置这些参数,因为这三项的参数是可变的,所以暂时只写前面名字:

t1=t.Label(text='进程数:')
t2=t.Label(text='CPU 使用率:')
t3=t.Label(text='物理内存:')
t1.place(x=10,y=580,width=120)
t2.place(x=150,y=580,width=120)
t3.place(x=300,y=580,width=120)
Copy after login

5)给多行文本框添加滚动条

我们可以使用模块Scrollbar来实现,安装滚动条之前需要做两件事情:

1.指定该组件的yscrollbarcommand参数为Scrollbar的set()方法

2.指定Scrollbar 的 command 参数为该组件的 yview() 方法

接下来我们实现它:

sb=t.Scrollbar(root)
sb.pack(side='left',fill='y')
text=t.Text(root,width=100,height=40)
text.place(x=10,y=36)
sb.config(command=text.yview) #文本框内容随滚动条滚动
text.config(yscrollcommand=sb.set(0.1,0.3)) #Y轴填充
Copy after login

6)添加状态栏文本标签

t1=t.Label(text='')
t2=t.Label(text='')
t3=t.Label(text='')
Copy after login

(注:这里只是隐藏部件,万不可用destroy销毁部件)

7)实现状态栏标签功能

现在我们来实现这三个标签的内容。想必大家刚刚应该看到了,上面的标签没有设置任何内容,那么这是为什么呢?我们都知道,一旦你把内容添加进去,它就会紧随其后并不会覆盖,所以初始值必须是空,才不至于不能覆盖值。那么我们来看下具体实现过程吧。

def jcs():
  t1.configure(text='进程数:'+str(len(psutil.pids())))
  root.after(3000,jcs)
def cpu():
  pp=str(ceil(psutil.cpu_percent(1)))
  t2.configure(text='CPU 使用率:'+pp+'%')
  root.after(1500,cpu)
def wlnc():
  f= psutil.virtual_memory().free #剩余内存
  t=psutil.virtual_memory().total#总内存
  wl= float(t-f)/float(t) #为使得最后值更精确,必须用float
  t3.configure(text='物理内存:'+str(floor(wl*100))+'%') 
  root.after(2000,wlnc)
Copy after login

这里的三个函数就是分别实现上面的三个功能的,最后将它添加到窗口事件即可。

8)功能编写

可以看到这页主要是系统运行的一些应用程序的名字,所以我们可以这样这里我们需要用到模块psutil 来获取系统的关键参数。

1.编写应用程序选项

应用程序选项包含进程号和进程名和进程文件路径,所以可以用psutil进行获取,方法如下:

text.insert('insert','进程号   '+'进程名      '+'  进程文件路径'+'\n')
  for y in psutil.pids():
    a=psutil.Process(y)
    if a.name()=='System Idle Process':
      continue
    else:
      text.insert('insert',str(y)+'     '+a.name()+'   '+a.exe()+'\n\n')
Copy after login

这样就可以将这些内容添加进来了。

2.编写进程选项

这里我们可以投机取巧,使用cmd中的tasklist命令,它可以打印出当前系统所有在运行的进程的信息。

mm=os.popen('tasklist')
text.insert('insert',mm.read())
Copy after login
3.编写服务选项

也是使用cmd中的sc 命令,它相当于一个扫描器,可以得到很多有用的信息。

mm=os.popen('sc query type= service')
text.insert('insert',mm.read())
Copy after login
4.编写性能选项

这个内容会比较多点,因为我们要得到比较多的参数和把组件放在多行文本框中,于是增加了一些冗余代码:

l1=t.Label(root,text='开机时间:')  tm=datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") 
  l2=t.Label(root,text=str(tm))
  l3=t.Label(root,text='当前时间:')
  l4=t.Label(root,text='')
  dq=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
  l4.configure(text=str(dq))
  l5=t.Label(root,text='物理内存使用情况(MB):')
  l6=t.Label(root,text='')
  jh=psutil.virtual_memory() #物理内存
  tt=int((jh.total)/1024/1024) #总量
  us=int((jh.used)/1024/1024) #使用量
  fr=int((jh.free)/1024/1024) #剩余量
  l6.configure(text='总量:' + str(tt) +'\n'+'使用:'+str(us) +'\n'+'剩余:'+str(fr))
  l7=t.Label(root,text='交换内存使用情况(MB):')
  l8=t.Label(root,text='')
  hj=psutil.swap_memory() #交换内存
  ht=int((hj.total)/1024/1024) 
  hu=int((hj.used)/1024/1024)
  hf=int((hj.free)/1024/1024)
  l8.configure(text='总量:' + str(ht) + '  '+'使用:'+str(hu) +'  '+'剩余:'+str(hf))
  text.window_create('insert',window=l1) #添加组件到多行文本框
  text.window_create('insert',window=l2)
  text.insert('insert','\n\n')
  text.window_create('insert',window=l3)
  text.window_create('insert',window=l4)
  text.insert('insert','\n\n')
  text.window_create('insert',window=l5)
  text.window_create('insert',window=l6)
  text.insert('insert','\n\n')
  text.window_create('insert',window=l7)
  text.window_create('insert',window=l8)
Copy after login
5.编写联网选项

这里我们只获取网卡的收发流量,因此:

n = psutil.net_io_counters()
r=str(float(n.bytes_recv / 1024 / 1024))+'MB'
s= str(float(n.bytes_sent / 1024 / 1024))+'MB'
text.insert('insert','网卡接收流量: '+str(r)+'\n'+'网卡发送流量:'+str(s)+'\n')
Copy after login
6.编写用户选项

这里我们需要获取当前的用户数:

use='    用户'+'      '+'     状态'+'\n'
text.insert('insert',use)
for y in psutil.users():
  text.insert('2.0',str(y.name)+'  '+'运行中。。。。'+'\n')
Copy after login

这样就完成了任务管理器的编写了。

Teach you step by step how to imitate a task manager using Python


3. Summary

Through the understanding of the task manager, we realize that the system Some crucial information, such as the process number can be obtained through the process name, the process name can be obtained through the process number, and the usage of the cmd command can be said to be quite user-friendly. I hope this article can help everyone.

The above is the detailed content of Teach you step by step how to imitate a task manager using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Nginx SSL Certificate Update Debian Tutorial Nginx SSL Certificate Update Debian Tutorial Apr 13, 2025 am 07:21 AM

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

How to configure HTTPS server in Debian OpenSSL How to configure HTTPS server in Debian OpenSSL Apr 13, 2025 am 11:03 AM

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

GitLab's plug-in development guide on Debian GitLab's plug-in development guide on Debian Apr 13, 2025 am 08:24 AM

Developing a GitLab plugin on Debian requires some specific steps and knowledge. Here is a basic guide to help you get started with this process. Installing GitLab First, you need to install GitLab on your Debian system. You can refer to the official installation manual of GitLab. Get API access token Before performing API integration, you need to get GitLab's API access token first. Open the GitLab dashboard, find the "AccessTokens" option in the user settings, and generate a new access token. Will be generated

What service is apache What service is apache Apr 13, 2025 pm 12:06 PM

Apache is the hero behind the Internet. It is not only a web server, but also a powerful platform that supports huge traffic and provides dynamic content. It provides extremely high flexibility through a modular design, allowing for the expansion of various functions as needed. However, modularity also presents configuration and performance challenges that require careful management. Apache is suitable for server scenarios that require highly customizable and meet complex needs.

See all articles