0

This is the code i'm working with

gameWindow = []
print("Detecting Game Window..")
def callback(hwnd, extra):
    rect = win32gui.GetWindowRect(hwnd)
    x1 = rect[0]
    y1 = rect[1]
    x2 = rect[2]
    y2 = rect[3]
    if win32gui.GetWindowText(hwnd) == "GameTest1":
        gameWindow.append(x1)
        gameWindow.append(y1)
        gameWindow.append(x2)
        gameWindow.append(y2)
    else:
        gameWindow = "None"

win32gui.EnumWindows(callback, None)

if type(gameWindow) != list:
    print("ERROR: Couldn't detect game window.")
    sys.exit()
print(gameWindow)

It suppose to append the coordinates of a window to a list.

But it throws me this error

Detecting Game Window..
Traceback (most recent call last):
  File "c:\Users\otter\Desktop\Tree Detector Test\main.py", line 55, in <module>
    win32gui.EnumWindows(callback, None)
  File "c:\Users\otter\Desktop\Tree Detector Test\main.py", line 48, in callback
    gameWindow.append(x1)
UnboundLocalError: local variable 'gameWindow' referenced before assignment

I have no idea why it's showing me this since i create gameWindow before even calling win32gui.EnumWindows(callback, None) function

SunAwtCanvas
  • 1,261
  • 1
  • 13
  • 38
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – manveti Mar 12 '20 at 01:08

1 Answers1

0

The reason is because you didn't globalize gameWindow in the function so when you run the function gameWindow isn't defined because the variables in the function start out as local variables meaning they only take effect in the function. In order to fix this you can just add:

global gameWindow

right after defining your function. Like this:

def callback(hwnd, extra):
    global gameWindow
    rect = win32gui.GetWindowRect(hwnd)
    ...
WangGang
  • 533
  • 3
  • 15