New to Python: Why do I get the error ImportError: cannot import name 'SetWindowPos' from 'win32con'

I am trying to put together some code that will pin the pygame window to the front – after doing some research I think the simplest way to do this in python 3.9 is is with

import win32gui
from win32con import SetWindowPos

SetWindowPos(pygame.display.get_wm_info()['window'], win32con.HWND_TOPMOST, 0,0,0,0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)

but I consistently get the error message

ImportError: cannot import name 'SetWindowPos' from 'win32con'

Anyone know why/how to fix this?

I’ve tried updating pip and making sure that my version of python and pip are compatable. I’ve tried the following commands:

python -m pip install pywin32
pip install pypiwin32
pip install win32con

I am not sure if this matters but I also installed win32gui and kept getting the error message


regardless of how many times I updated pip/python and made sure they were compatable

>Solution :

The error message suggests that the name ‘SetWindowPos’ cannot be imported from the ‘win32con’ module. This could be because the module does not have that particular function, or it could be due to a version mismatch or installation issue.

Here are a few steps you could try to resolve the issue:

  1. Check the version of pywin32 module you have installed. Make sure it is the latest version compatible with your Python version.

  2. Instead of importing SetWindowPos from win32con, try importing it directly from win32gui:

    from win32gui import SetWindowPos

    This is because SetWindowPos is actually part of the win32gui module, not win32con.

  3. Verify that all the required modules are installed. Try running the following commands to ensure that all the modules are installed correctly:

    pip install pywin32
    pip install pygame

    You may also want to try uninstalling and reinstalling these modules to make sure there are no conflicts.

  4. Make sure you are using the correct syntax for SetWindowPos. Here is an example of how to use it:

    hwnd = pygame.display.get_wm_info()["window"]
    SetWindowPos(hwnd, -1, 0, 0, 0, 0, 0x0001 | 0x0002)

    In this example, hwnd is the window handle returned by pygame.display.get_wm_info()["window"].

Hopefully, one of these steps will help you resolve the issue.

Leave a Reply