python - Pygame icon() 函数不改变全局变量
问题描述
我有一个功能,允许用户单击图标并设置一个布尔值,以便主循环知道要执行哪个操作。该代码旨在用作单击喷枪图标->设置airbrushMode
为true->返回airbrushMode
以便paintScreen()
可以检测到它->执行airbrushMode
while循环中设置的操作。我在打印语句中添加了定位问题。变量确实发生了变化,但没有返回变量,并且喷枪功能不起作用。当我airbrushMode
在内部设置为 truepaintScreen()
但在函数中设置为 false 时,它确实有效,在函数外部都不起作用。
主要功能
def paintScreen():
airbrushMode = False
paint = True
gameDisplay.fill(cyan)
message_to_screen('Welcome to PyPaint', black, -300, 'large')
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
pygame.draw.rect(gameDisplay, white, (50, 120, displayWidth - 100, displayHeight - 240))
while paint:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
button('X', 20, 20, 50, 50, red, lightRed, action = 'quit')
icon(airbrushIcon, white, 50, displayHeight - 101, 51, 51, white, grey, 'airbrush')
icon(pencilIcon, white, 140, displayHeight - 101, 51, 51, white, grey, 'pencil')
icon(calligraphyIcon, white, 230, displayHeight - 101, 51, 51, white, grey, 'calligraphy')
pygame.display.update()
if cur[0] >= 50 <= displayWidth - 50 and cur[1] >= 120 <= displayHeight - 120:
if airbrushMode == True:
airbrush()
创建图标并检测动作,然后返回它的函数
def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
gameDisplay.blit(icon, (x, y))
if click[0] == 1 and action != None: #if clicked
print('click')
if action == 'quit':
pygame.quit()
quit()
elif action == 'airbrush':
airbrushMode = True
print('airbrush set')
return airbrushMode
print('airbrush active')
解决方案
您的问题是icon
不尝试更改任何全局变量;它严格处理其输入参数和局部变量。如果您希望它更改自己范围之外的变量,则需要添加
global airbrushMode
在你的功能的顶部。
此外,如果您希望paintScreen
识别全局变量,则必须具有该变量的全局存在(顶级用法),或者paintScreen
还需要global
声明。
有关完整的详细信息,请在 Python 中查找全局变量。
推荐阅读
- mysql - 如果表 1 中的列不为 Null,则更新表 2
- oauth - 如何确定过期的访问令牌?
- php - 通过 curl 将数据发布到 php。jsondata.php 没有给出 json 输出
- c# - 为什么使用内部等待任务的映射函数调用 Select() 会返回任务列表而不是它们的结果?
- javascript - document.getElementById().children.length - 无法读取 null 的属性“孩子”
- c# - Serilog 解构.通过转换
() 不工作 - reactjs - 将查询结果传递给下一个视图时做出反应,它是空的
- java - 捕获第一个单词并分配一个变量
- css - 页面末尾错误(XML SVG)和 CSS 不起作用
- c++ - Unable to modify FD epoll: No such file or directory