button.Button 类错误:'button_list 未定义'..... :( 使用 replit [英] button.Button class error:'button_list not defined'..... :( using replit
问题描述
我正在学习为平台游戏创建地图编辑器的在线教程,但我的导入按钮功能不起作用,显示错误button_list 未定义",但我不明白这是为什么,因为我已经将其定义为空列表?我有按钮类的以下代码.
I am following a tutorial online creating a map editor for a platform game and my import button feature is not working, showing error 'button_list not defined' but I can not see why this is as I defined it as empty list already? I have the following code for the button class.
import pygame
import button
def button():
button_list = []
button_col = 0
button_row = 0
for i in range(len(img_list)):
tile_button = button.Button(SCREEN_WIDTH + (75 * button_col) + 50, 75 * button_row + 50, img_list[i], 1)
button_list.append(tile_button)
button_col += 1
if button_col == 3:
button_row += 1
button_col = 0
这没有错误并且运行正常,(当然屏幕上没有任何内容)但是当我使用以下代码绘制它时发生错误......请帮忙!
This has no errors and runs OK, (nothing on screen of course) but when I draw it with the following code the error occurs.... please help!
for i in button_list:
i.draw(screen)
推荐答案
你必须使用 global
语句 如果你想在函数内的全局命名空间中定义一个变量:
You have to use the global
statement if you want to define a variable in the global namespace within a function:
def button():
global button_list
button_list = []
button_col = 0
button_row = 0
for i in range(len(img_list)):
# [...]
button()
for i in button_list:
i.draw(screen)
或者,您可以在全局命名空间中定义 button_list
:
button_list = []
def button():
button_col = 0
button_row = 0
for i in range(len(img_list)):
tile_button = button.Button(SCREEN_WIDTH + (75 * button_col) + 50, 75 * button_row + 50, img_list[i], 1)
button_list.append(tile_button)
button_col += 1
if button_col == 3:
button_row += 1
button_col = 0
这篇关于button.Button 类错误:'button_list 未定义'..... :( 使用 replit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!