无法获得按钮以调用内部函数,我不确定为什么



我对python和pygame相当陌生,并且一直在与函数的想法作斗争-我似乎无法从子函数调用主函数的按钮。我可以使它在主要功能的全部工作,但这不是我要做的,我想要能够调用一个按钮进入主要功能,当它是需要的。我不知道我错过了什么。

import sys
import pygame
import button
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Main Page")
icon = pygame.image.load('Sprites/icons8-robber-32.png')
clock = pygame.time.Clock()
running = True
start_image = pygame.image.load('Sprites/play.png').convert_alpha()
def buttons(arg1):
start_button = button.Button(350, 100, start_image, 0.2)
arg1(start_button)
return arg1
while running:
time_delta = clock.tick(60)/1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if start_button.draw(screen):
print("no")
pygame.display.update()

buttons(arg1)
pygame.QUIT()
sys.exit()

谢谢!

编辑:包括按钮代码

import pygame
class Button():
def __init__(self, x, y, image, scale):
width = image.get_width()
height = image.get_height()
self.image = pygame.transform.scale(image, (int(width*scale), int(height*scale)))
self.rect = self.image.get_rect()
self.rect.topleft = (x,y)
self.clicked = False
def draw(self, surface):
action = False
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
self.clicked = True
action = True

if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
surface.blit(self.image, (self.rect.x, self.rect.y))
return action

首先你让你的按钮在主while True循环之后。

在启动主循环之前创建按钮,它应该是一个全局变量。我修改了你的代码,定义了start_button。您可以创建一个新按钮,根据参数为其分配属性等等。然后,您可以返回按钮并将其存储在一个全局变量中。

import sys
import pygame
import button
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Main Page")
icon = pygame.image.load('Sprites/icons8-robber-32.png')
clock = pygame.time.Clock()
running = True
start_image = pygame.image.load('Sprites/play.png').convert_alpha()
def create_button(args): #Give your arguments
button = button.Button(350, 100, start_image, 0.2)
# Your code...
return button
start_button = create_button(args)
while running:
time_delta = clock.tick(60)/1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if start_button.draw(screen):
print("no")
pygame.display.update()
pygame.QUIT()
sys.exit()

最新更新