需求場景
使用PC的打工人,在編寫每日的復(fù)盤日報時,總會有點兒痛苦,感嘆今天一天時間都去哪兒了。
軟件截圖


image.png

顯示耗時TOP5的窗口

image.png

image.png
# encoding=utf-8
import ctypes
import inspect
import threading
import time
import tkinter
import tkinter.messagebox
import win32gui
import matplotlib.pyplot as plt
def returnSum(myDict):
temp_sum = 0
for i in myDict:
temp_sum = temp_sum + myDict[i]
return temp_sum
def drawPie():
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用來正常顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus'] = False # 用來正常顯示負(fù)號
temp = sorted(a.items(), key=lambda x: x[1], reverse=True)
labels = temp[0][0], temp[1][0], temp[2][0], temp[3][0], temp[4][0]
sizes = [temp[0][1], temp[1][1], temp[2][1], temp[4][1], temp[4][1]]
explode = (0.4, 0.1, 0.1, 0.1, 0.1) # only "explode" the 2nd slice (i.e. 'Hogs');這里的四個參數(shù),指分開的距離,值越大分得越開。
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
# plt.savefig('Demo_official.jpg') # 保存圖片
plt.show()
def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
print("關(guān)閉")
def getHandle():
while True:
if b['state']:
# 獲取前臺窗口的句柄
handle = win32gui.GetForegroundWindow()
# 根據(jù)前臺窗口的句柄獲取線程tid和進(jìn)程pid
# tid, pid = win32process.GetWindowThreadProcessId(handle)
# 根據(jù)前臺窗口的進(jìn)程pid獲取進(jìn)程名稱
# process_name = psutil.Process(pid).name()
w_name = win32gui.GetWindowText(handle)
# 如果前端窗口存在字典中,則在該key對應(yīng)的value+1;否則在字典中新建一個key并賦值為1。
if w_name in a:
a[w_name] = a[w_name] + 1
else:
a[w_name] = 1
if len(a.keys()) >= 5:
show()
btn4['state'] = tkinter.NORMAL
tkinter.Label(root, width=100, height=2, text="運(yùn)行窗口數(shù)量為:" + str(len(a.keys())), font=fontset,
bg='#D1EEEE').grid(row=0, column=1)
else:
tkinter.Label(root, width=100, height=2, text="運(yùn)行窗口數(shù)量不足5個!", font=fontset, bg='#D1EEEE').grid(row=0,
column=1)
tkinter.Label(root, text=returnSum(a), width=10, height=2, bg='#D1EEEE', anchor='center',
font=fontset).grid(row=0, column=2)
time.sleep(1)
else:
time.sleep(1)
pass
def show():
s1 = sorted(a.items(), key=lambda x: x[1], reverse=True)
s2 = s1[0:5]
# 在窗口內(nèi)創(chuàng)建按鈕,以表格的形式依次排列
for i in range(5):
tkinter.Label(root, text=s2[i][0], width=100, height=2, bg='#D1EEEE', anchor='e', justify='right',
wraplength=800, font=fontset).grid(row=i + 1, column=1)
tkinter.Label(root, text=s2[i][1], width=10, height=2, bg='#D1EEEE', anchor='center', justify='right',
font=fontset).grid(row=i + 1, column=2)
# # 在第5行第11列添加一個Label標(biāo)簽
# Label(win, text="C語言中文網(wǎng)", fg='blue', font=('楷體', 12, 'bold')).grid(row=4, column=11)
# text.delete("1.0", END)
# text.insert(END, s2)
def start_tj():
b['state'] = True
btn1['state'] = tkinter.DISABLED
btn2['state'] = tkinter.NORMAL
def stop_tj():
b['state'] = False
btn2['state'] = tkinter.DISABLED
btn1['state'] = tkinter.NORMAL
def save_tj():
s = sorted(a.items(), key=lambda x: x[1], reverse=True)
fw = open("test.txt", 'w', encoding='utf-8') # 將要輸出保存的文件地址
for line in range(len(s)): # 讀取的文件
fw.write(s[line][0])
fw.write("++++++++++++++++++++++++++++++++++++++++")
fw.write(str(s[line][1]))
fw.write("\n") # 換行
if __name__ == '__main__':
a = {"processName1": 1}
b = {'state': False}
root = tkinter.Tk()
root.minsize(980, 0)
root.maxsize(980, 300)
root.title("前端窗口時間統(tǒng)計程序")
fontset = ('黑體', 12)
# text = tkinter.Text(root, width=100, wrap="word")
# text.insert(END, "前端窗口時間統(tǒng)計程序")
# text.place(x=10, y=90)
#
# label1 = tkinter.Label(root, text='213') # 生成標(biāo)簽并將標(biāo)簽添加到主窗口
# label1.place(x=10, y=90)
btn1 = tkinter.Button(root, text='開始', width=10, height=2, command=start_tj) # 生成button
btn1.grid(row=0, column=0)
btn2 = tkinter.Button(root, text='暫停', width=10, height=2, command=stop_tj) # 生成button
btn2.grid(row=1, column=0)
btn3 = tkinter.Button(root, text='保存結(jié)果', width=10, height=2, command=save_tj) # 生成button
btn3.grid(row=2, column=0)
btn4 = tkinter.Button(root, text='統(tǒng)計圖', width=10, height=2, command=drawPie) # 生成button
btn4.grid(row=3, column=0)
btn4['state'] = tkinter.DISABLED
btn5 = tkinter.Button(root, text='功能預(yù)留', width=10, height=2, command=drawPie) # 生成button
btn5.grid(row=4, column=0)
btn5['state'] = tkinter.DISABLED
btn6 = tkinter.Button(root, text='功能預(yù)留', width=10, height=2, command=drawPie) # 生成button
btn6.grid(row=5, column=0)
btn6['state'] = tkinter.DISABLED
t1 = threading.Thread(target=getHandle)
t1.start() # 啟動線程,即讓線程開始執(zhí)行
# t2 = threading.Thread(target=drawPie((u'周', '吳', '鄭', '王'),(15, 30, 45, 10)))
# t2.start() # 啟動線程,即讓線程開始執(zhí)行
root.mainloop()
stop_thread(t1)