So I'm trying to use both win32gui and Pandas to get a dataframe (df) of windows that are open. Below is what I wrote. I end up with an error. How can I get one dataframe returned?
# 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
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)
So the key to getting the dataframe out of the function is to use a global variable. This variable must be state as global inside the function so there is not confusion and python does not consider it as local variable. Here is the code.
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)