我需要使pygame窗口位于其他窗口之上。我在这次讨论中找到了一种方法:
如何使python窗口运行为"总是名列前茅";?
但这在我的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
要使ctypes.windll
工作,必须首先配置函数参数的类型(如果在32位机器上,则不必配置IIRC(。
所以你的代码应该是这样的:
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()