如何将 pygame 窗口固定在顶部?

问题描述 投票:0回答:2

我需要让 pygame 窗口保持在其他窗口之上。我在这次讨论中找到了一种方法:

如何让python窗口以“Always On Top”方式运行?

但这在我的Python代码中不起作用。

这是我的代码:

# Imports
import pygame as pg
from ctypes import windll

SetWindowPos = windll.user32.SetWindowPos

pg.init()
win = pg.display.set_mode((200, 30))

x, y = 100, 100
# Pin Window to the top
SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 0x0001)


#Main Loop
run = True
while run:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run = False
            break
python python-3.x windows pygame always-on-top
2个回答
3
投票

要使

ctypes.windll
工作,您必须首先配置函数参数的类型(IIRC,如果您使用的是 32 位计算机,则不必这样做)。

所以你的代码应该是这样的:

import pygame
import ctypes
from ctypes import wintypes 

def main():
    pygame.init()
    screen = pygame.display.set_mode((400, 200))
    
    hwnd = pygame.display.get_wm_info()['window']
    
    user32 = ctypes.WinDLL("user32")
    user32.SetWindowPos.restype = wintypes.HWND
    user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, wintypes.INT, wintypes.INT, wintypes.INT, wintypes.INT, wintypes.UINT]
    user32.SetWindowPos(hwnd, -1, 600, 300, 0, 0, 0x0001)
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
        screen.fill('grey')
        pygame.display.flip()

if __name__ == '__main__':
    main()

我更喜欢使用 pywin32 包,因为函数可以工作并且你需要的常量都可用。

import pygame
import win32gui
import win32con

def main():
    pygame.init()
    screen = pygame.display.set_mode((400, 200))

    hwnd = win32gui.GetForegroundWindow()

    win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 600, 300, 0, 0, win32con.SWP_NOSIZE)
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
        screen.fill('grey')
        pygame.display.flip()

if __name__ == '__main__':
    main()

0
投票

Efectivamante,我的解决方案允许 pygame 的通风,谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.