Pygame设置窗口在最上层但不改变位置

2 投票
5 回答
8806 浏览
提问于 2025-04-18 17:46

我在下面这个话题中发现了相关内容:如何让Python窗口始终保持在最上面?

我知道怎么把一个窗口放到最上面,但我想让它保持在同一个位置。作者提到他找到了一种方法来获取窗口的x和y坐标。我想知道我该怎么做才能实现这个!

我该如何获取pygame窗口的x和y坐标?也许这样做不是个好办法。

我想要的效果是,当我通过某个函数调用触发时,窗口能够跳到最上面。

对于玩过《英雄联盟》的人来说,当游戏开始时,窗口会跳到最上面,并且保持在同样的位置。

5 个回答

0

我在使用Windows 11系统,Python版本是3.11.2,但不知道为什么,来自windll.user32库的SetWindowPos函数不管用。不过,来自win32gui库的同样SetWindowPos函数却能正常工作。只要按照之前@ZiyadCodes给出的那个答案去做就行。

要安装所需的库:

$ pip install win32gui
$ pip install win32con

要让pygame窗口始终保持在最上面:

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)
0

获取当前窗口位置:

from ctypes import POINTER, WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HWND, RECT


# get our window ID:
hwnd = pygame.display.get_wm_info()["window"]

# Jump through all the ctypes hoops:
prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
paramflags = (1, "hwnd"), (2, "lprect")

GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)

# finally get our data!
rect = GetWindowRect(hwnd)
print "top, left, bottom, right: ", rect.top, rect.left, rect.bottom, rect.right

# bottom, top, left, right:  644 98 124 644

将窗口放到最前面:

x = rect.left
y = rect.top
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
1

这个方法对我有效

import win32gui
import win32con

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

窗口没有移动,因为我用了 SWP_NOMOVE 这个标记

5

这里有一个更简短的解决方案,使用的是同一个函数

from ctypes import windll
SetWindowPos = windll.user32.SetWindowPos

NOSIZE = 1
NOMOVE = 2
TOPMOST = -1
NOT_TOPMOST = -2

def alwaysOnTop(yesOrNo):
    zorder = (NOT_TOPMOST, TOPMOST)[yesOrNo] # choose a flag according to bool
    hwnd = pygame.display.get_wm_info()['window'] # handle to the window
    SetWindowPos(hwnd, zorder, 0, 0, 0, 0, NOMOVE|NOSIZE)
4

我找到了一种看起来很不错的解决办法:

#!/usr/bin/python
# -*- coding: utf-8 -*-


from ctypes import windll, Structure, c_long, byref #windows only


class RECT(Structure):
    _fields_ = [
    ('left',    c_long),
    ('top',     c_long),
    ('right',   c_long),
    ('bottom',  c_long),
    ]
    def width(self):  return self.right  - self.left
    def height(self): return self.bottom - self.top


def onTop(window):
    SetWindowPos = windll.user32.SetWindowPos
    GetWindowRect = windll.user32.GetWindowRect
    rc = RECT()
    GetWindowRect(window, byref(rc))
    SetWindowPos(window, -1, rc.left, rc.top, 0, 0, 0x0001)

现在,要把一个窗口放在最上面,只需调用 onTop(pygame.display.get_wm_info()['window']) 来处理你的pygame窗口。

撰写回答