如何获取每个打开的 window 的名称列表并将其放入数据框中?

How to get a list of the name of every open window and place that into dataframe?

所以我尝试同时使用 win32gui 和 Pandas 来获取 windows 的打开的数据帧 (df)。下面是我写的。我最终遇到了一个错误。如何返回一个数据帧?

# info http://timgolden.me.uk/pywin32-docs/win32gui__EnumWindows_meth.html

import win32gui
import pandas as pd

def winEnumHandler( hwnd, dfx ):
    if win32gui.IsWindowVisible( hwnd ) and len(win32gui.GetWindowText( hwnd ))>0 :
    idv = hex(hwnd)
    winv = win32gui.GetWindowText(hwnd)
    df = pd.DataFrame({'ID' : idv , 'Window': winv}, index = ['0'])

    frames  = [dfx, df]
    dfx = pd.concat(frames)
    # print(dfx) 
    return dfx # Comment out this and it runs but not the result I want.

dfx= pd.DataFrame() # empty dataframe
win32gui.EnumWindows( winEnumHandler, dfx )
print(dfx)

回溯

Traceback (most recent call last):
  File "c:\Users\s...\Python\List of windows.py", line 19, in <module>
    win32gui.EnumWindows( winEnumHandler, dfx )
TypeError: an integer is required (got type DataFrame)

所以从函数中获取数据帧的关键是使用全局变量。此变量必须在函数内部声明为全局变量,因此不会造成混淆,并且 python 不会将其视为局部变量。这是代码。

import win32gui
import pandas as pd

dfx = pd.DataFrame() 
i = 0

def winEnumHandler( hwnd, x ):
    global dfx, i

    if win32gui.IsWindowVisible( hwnd ) and len(win32gui.GetWindowText( hwnd ))>0 :
        idv = hex(hwnd)
        winv = win32gui.GetWindowText(hwnd)
        df = pd.DataFrame({'ID' : idv , 'Window': winv}, index = [i])
        frames  = [dfx, df]
        dfx = pd.concat(frames)
        i += 1

win32gui.EnumWindows( winEnumHandler, i )
print(dfx)