我用pygame用python编写了一个程序,这样当你按下屏幕上的一个按钮时,它就会执行一个命令。我是通过define来实现的,但是我似乎不能使用这个命令。这是我的代码(顺便说一句,我使用的是python2.7.11)
from time import sleep
import pygame
from pygame.locals import *
white = (255, 255, 255)
red = (255,0,0)
black = (0,0,0)
green = (0,255,0)
blue = (0,0,255)
yellow = (135,135,0)#(kinda green)
pygame.init()
screen = pygame.display.set_mode((300,200))
pygame.display.set_caption('Testing')
running = True
def msg():
print (20)
def button(posX,posY,length,width,color,color2,color3,command):
a = (0,0)
b = (posX,posY)
c = (posX+length,posY+width)
while 1:
sleep (0.001)
for event in pygame.event.get():
screen.fill(white)
if event.type == QUIT:
running = False
if event.type == KEYDOWN and event.key == K_ESCAPE:
running = False
a = pygame.mouse.get_pos()
if (a >= b) & (a <= c):
if (event.type == MOUSEBUTTONDOWN):
pygame.draw.rect(screen, color3, [posX, posY,length,width])
pygame.display.flip()
command
else:
pygame.draw.rect(screen, color2, [posX, posY,length,width])
pygame.display.flip()
else:
pygame.draw.rect(screen, color, [posX, posY,length,width])
pygame.display.flip()
pygame.display.quit()
button(60,60,100,100,red,black,green,msg())
如您所见,我正在从单击按钮时运行的变量命令调用另一个define。当我运行这个并点击按钮时,没有错误,只是什么都没有发生。有人能告诉我怎么做吗?我在谷歌上到处搜索,但没有找到任何相关信息
当您将
msg()
放在参数列表中的button
时,您不是将函数作为参数传递,而是立即调用它,并将其返回值(None
在本例中)作为参数传递。去掉括号,您将传递对函数的引用:现在您只需要修复从
button
函数内部调用命令的问题。不只是命名它,command
,而是通过在结尾添加括号来调用它:相关问题 更多 >
编程相关推荐