簡體   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