gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:09:10 24 4
gpt4 key购买 nike

我需要让一个 pygame 窗口停留在其他窗口的顶部。我在这个讨论中找到了一种方法:
How to make python window run as "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

最佳答案

对于 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()

关于python - 如何将pygame窗口固定在顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65683617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com