繁体   English   中英

如何使用 PyGame 制作“退出”按钮单击事件以关闭程序

[英]How to make a “Quit” button click event to close a program using PyGame

我第一次使用 Pygame 库,我在制作一个简单的按钮时遇到了一些麻烦,其点击事件将关闭我的程序。 我按以下方式分割了我的代码:

App.py,其中包含我的主循环:

import pygame
from pygame.locals import *
from widgets import *

class App():

    # creates object
    def __init__(self):

        self._running = True
        self._display_surf = None
        self.size = self.weight, self.height = 1000, 500

        self.button_1 = rect_Button(((255,255,255)),(500,250),"Quit")

    # initializes all PyGame modules
    # create main display & uses hardware acceleration
    def on_init(self):

        pygame.init()
        self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._running = True
 
    def on_event(self, event):

        if event.type == pygame.QUIT:
            self._running = False

        #if event.type == MOUSEBUTTONUP:
            #self._running = False

        if self.button_1.click_State:
            # testing button
            print("closing...")

    def on_loop(self):
        pass

    def on_render(self):
        rect_button_1 = pygame.draw.rect(self._display_surf,self.button_1.color,self.button_1.container())
        self._display_surf.blit(self.button_1.display_Text,rect_button_1)
        pygame.display.update()

    def on_cleanup(self):

        pygame.quit()

    def on_click(self):

        pass
 
    def on_execute(self):

        if self.on_init() == False:
            self._running = False
 
        while( self._running ):

            for event in pygame.event.get():
                self.on_event(event)

            self.on_loop()
            self.on_render()

        self.on_cleanup()

widgets.py,我将为 Pygame 上未内置的小部件创建类:

import pygame
from pygame.locals import *

pygame.init()

class rect_Button():

    def __init__(self, color, pos, text):

        self.font = pygame.font.Font('freesansbold.ttf',32)
        self.display_Text = self.font.render(text,True,((200,0,0)),None)
        self.mouse = pygame.mouse.get_pos()
        self.click = pygame.mouse.get_pressed()
        self.width = self.font.size(text)[0]
        self.height = self.font.size(text)[1]
        self.color = color
        self.pos_X = pos[0]
        self.pos_Y = pos[1]

    def container(self):
        return pygame.Rect(self.pos_X,self.pos_Y,self.width,self.height)

    def click_State(self):
        if self.pos_X+self.width > mouse[0] > self.pos_X and self.pos_Y+self.height > mouse[1] > self.pos_Y:
            if self.click[0]==True:
                return True
        else:
            return False

最后是 game.py,我在其中创建了应用程序 object:

import pygame
from pygame.locals import *
from app import *

if __name__ == "__main__" :
    theApp = App()
    theApp.on_execute()

我的问题是我想点击我创建的退出按钮并关闭我的程序。 为了测试它,每当我在按钮内单击时,我都会让它打印“关闭...”。 但是,每当我在程序 window 中移动鼠标时,它就会连续打印。 我应该如何告诉我的代码从按钮 object 获取单击按钮的信息,运行事件并关闭 window?

谢谢

很难遵循您的代码,但我建议创建一个单独的 function 来处理事件检查。 当您想检查是否按下按钮时,在检查pygame.event.get()循环下更容易使用以下命令:

elif event.type == pygame.MOUSEBUTTONDOWN:
    mouse_x, mouse_y = pygame.mouse.get_pos()
    button_clicked = easy_button.rect.collidepoint(mouse_x, mouse_y)

    if button_hard_clicked and self._running: # checks of active program/click
       # Whatever you want to do if the button is clicked
       self._running = False 

查看我的星球大战 pygame 拍摄程序,它也实现了一个按钮。 希望这会有所帮助。 按钮的代码可以在game_functions.pymain.py文件中找到。 链接在这里

截至目前,

if self.button_1.click_State:

不会调用 click_State() 要解决此问题,请在 click_State 末尾添加 () 以调用 function。 另外,如上写行时,语句的rest会自动进行。 (因此所有的“关闭......”)

if self.button_1.click_State():

上面的行更接近,但程序没有检查它是否匹配任何内容。 要解决此问题,请更改为:

if self.button_1.click_State() == True:

从那里您可以插入代码的 rest 以关闭程序。 希望我能有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM