【问题标题】:Change size of window but center on monitor screen更改窗口大小但在监视器屏幕上居中
【发布时间】:2022-10-06 12:08:21
【问题描述】:

我想用一个较小的窗口(比如 100x100)启动程序,并根据用户对小屏幕的操作来调整大小。在下面的示例中,它调整为 800x800。

我遇到的一个问题是,在调整大小时,它不会在显示器上居中,并且取决于我调整到的大小,它将不在显示器上。有没有办法调整pygame窗口的大小,使其保持在监视器屏幕的中心?

我能找到的大多数答案都是让游戏全屏显示,但我想避免这种情况。我还找到了一种解决方法Pygame Display Position While Running,您可以在其中退出并再次初始化,但这似乎并不理想。

这是演示该问题的代码:

import pygame

if __name__ == \"__main__\":
    pygame.init()
    screen = pygame.display.set_mode([100, 100])
    screen.fill((255, 255, 255))
    pygame.display.update()
    menu = True
    size = [-1, -1]
    while menu:
        for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            menu = False
            size = [800, 800]
    screen = pygame.display.set_mode(size)
    screen.fill((255, 255, 255))
    game = True
    while game:
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                game = False
  • 我认为使用纯 pygame 是不可能的。
  • 您可以在创建新窗口之前致电pygame.display.quit()

标签: python pygame


【解决方案1】:

正如@Jerry 在 cmets 中建议的那样,您可以在调用pygame.display.set_mode((width, height)) 之前使用pygame.display.quit(),甚至更简单,您可以简单地使用pygame.quit()

这是一个简单的例子:

import pygame as pg
import sys

def screen_resize(amount):
    # I dislike using the "global" keyword but I wanted to keep my example short
    global screen
    new_size = [screen.get_width() + amount, screen.get_height() + amount]

    # If the new size is too small or too big I simple exit the function
    if new_size[0] > MAX_SIZE: return
    if new_size[0] < MIN_SIZE: return

    # pg.quit() before resizing so that the new display is centered to your screen
    pg.quit()
    screen = pg.display.set_mode(new_size)

if __name__ == "__main__":
    MIN_SIZE, MAX_SIZE = 100, 500
    screen = pg.display.set_mode([MIN_SIZE, MIN_SIZE])

    while True:
        for evt in pg.event.get():
            if evt.type == pg.QUIT:
                pg.quit()
                sys.exit()
            
            # I resize the window when I press "p" or "m" ("p" for "plus", "m" for "minus")
            elif evt.type == pg.KEYDOWN:
                if evt.key == pg.K_p:
                    screen_resize(100)
                elif evt.key == pg.K_m:
                    screen_resize(-100)

我相信你可以想办法把这个原则融入你的项目。如果答案不清楚,请随时要求澄清,我将编辑我的答案。

【讨论】:

    【解决方案2】:

    https://github.com/pygame/pygame/issues/3464

    这是 pygame 的一个问题,应该在下一个版本中修复。

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 2010-12-23
      • 2011-06-03
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多