我想这会成功的import psutil, win32process, win32gui, time
def active_window_process_name():
pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow()) #This produces a list of PIDs active window relates to
print(psutil.Process(pid[-1]).name()) #pid[-1] is the most likely to survive last longer
time.sleep(3) #click on a window you like and wait 3 seconds
active_window_process_name()
假设您已经安装了psutil和win32模块
运行此程序以获得更好的理解import threading, win32gui, win32process, psutil
from tkinter import *
root = Tk()
s = StringVar()
def active_window_process_name():
try:
pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
return(psutil.Process(pid[-1]).name())
except:
pass
def to_label():
global s
while True:
s.set(active_window_process_name())
return
Label(root,textvariable=s).pack()
if __name__ == "__main__":
t = threading.Thread(target = to_label)
t.start()
root.mainloop()