Pygame窗口冻结并停止响应,我该如何解决?

时间:2019-06-14 13:03:57

标签: python python-3.x pygame

我正在创建游戏,但是我的GUI的按钮类有问题。也没有编译错误,也没有运行时错误。唯一的问题是,在运行时它将立即冻结pygame窗口。我不知道该怎么解决。

我尝试摆弄回调函数(已将其完全删除)以及update和draw循环,但似乎没有任何作用。

Python 3.7.0和Pygame 1.9.4

按钮类:

import sys
import time
import pygame
pygame.init()

class button:
    def __init__(self, txt, location, bg=(255,255,255),fg=(0,0,0),size=(80,30),font_name="Times New Roman",font_size=16):
        #bg is the colour of the button
        #fg is the colour of the text
        #location refers to the center points of the button
        self.colour = bg
        self.bg = bg
        self.fg = fg
        self.size = size
        self.font = pygame.font.SysFont(font_name,font_size)
        self.txt = txt
        self.txt_surf = self.font.render(self.txt, 1, self.fg)
        self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])
        self.surface = pygame.surface.Surface(size)
        self.rect = self.surface.get_rect(center=location)
    def mouseover(self):
        self.bg = self.colour
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            self.bg = (200,200,200)
    def draw(self, screen):
        self.mouseover()
        self.surface.fill(self.bg)
        self.surface.blit(self.txt_surf, self.txt_rect)
        screen.blit(self.surface, self.rect)

实际更新/绘制循环

import gui
import pygame
import sys
import time
import win32api
pygame.init()

screen = pygame.display.set_mode((400,400))
button1 = gui.button("No", (200,200))
intro = True
while intro:
    screen.fill((255,255,255))
    button1.draw(screen)
    if win32api.GetKeyState(0x01) == -127 or win32api.GetKeyState(0x01) == -128:
        if button1.rect.collidepoint(pygame.mouse.get_pos()):
            intro = False
            pygame.quit()
            sys.exit()
    pygame.display.flip()
    pygame.time.wait(20)

我真的只希望窗口在运行时停止冻结,并真正让按钮工作。当您按下中间的按钮时,它应该立即退出应用程序。其实不行。

1 个答案:

答案 0 :(得分:2)

您必须让pygame通过调用pygame.event.get(或pygame.event.pump来处理事件队列中的事件,但您应坚持使用get)。

否则,队列将填满,新事件将被丢弃。这包括一些内部事件,这些事件告诉您的操作系统绘制窗口等,因此您的窗口将冻结。

此外,没有理由使用win32api来获取键盘的状态(您可以使用pygame.key.get_pressed来代替),但这是另一个主题。