Fully transparent windows in Pygame?

前端 未结 2 598
栀梦
栀梦 2020-12-11 04:39

Is it possible to get a fully transparent window in Pygame (see the desktop through it)? I\'ve found how to create a window without a frame, but there doesn\'t seem to be a

相关标签:
2条回答
  • 2020-12-11 05:15

    PyGame uses SDL, which does not support transparent windows. Although at least on Linux making it transparent is done by the window manager, not the application.

    0 讨论(0)
  • 2020-12-11 05:20

    On Windows, you can create a solid background color then set the window's transparency color with the Win32 API function SetLayeredWindowAttributes(). (Called with pywin32)

    Code:

    import pygame
    import win32api
    import win32con
    import win32gui
    
    pygame.init()
    screen = pygame.display.set_mode((800, 600)) # For borderless, use pygame.NOFRAME
    done = False
    fuchsia = (255, 0, 128)  # Transparency color
    dark_red = (139, 0, 0)
    
    # Create layered window
    hwnd = pygame.display.get_wm_info()["window"]
    win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
                           win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
    # Set window transparency color
    win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(*fuchsia), 0, win32con.LWA_COLORKEY)
    
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
    
        screen.fill(fuchsia)  # Transparent background
        pygame.draw.rect(screen, dark_red, pygame.Rect(30, 30, 60, 60))
        pygame.display.update()
    

    Result:

    Explanation:

    Any part of the window using your transparency color will be fully transparent. You can view and interact with any desktop icons or programs located behind your game window.

    To remove the window border, you can set Pygame's display mode to NOFRAME.

    screen = pygame.display.set_mode((800, 600), pygame.NOFRAME)
    

    See Also:

    • Stack Overflow: Make a window transparent using Win32?
    • Stack Overflow: Transparent hwnd window
    • Microsoft: Layered Windows
    • Microsoft: SetLayeredWindowAttributes function
    0 讨论(0)
提交回复
热议问题