如何修复Python代码中的NameError: name 'pos' is not defined错误?
解决Pygame中NameError: name 'pos' is not defined错误
你的错误根源是处理鼠标事件时,未获取鼠标坐标就调用了isOver方法,另外代码还有几处细节问题需要修正:
- 未定义
pos变量:在MOUSEMOTION和MOUSEBUTTONDOWN事件中,需要通过event.pos获取当前鼠标的(x,y)坐标 - 重复定义
isOver方法:代码里两次实现了同一个方法,保留一份即可 - 代码缩进/格式错误:
DRAW_WINDOW函数和main函数内的代码缩进混乱,需要规范 - 缺失Pygame基础初始化:原代码没有初始化Pygame和创建窗口,这是程序运行的必要步骤
以下是修正后的完整代码:
import pygame class button(): def __init__(self, color, x, y, width, height, text=''): self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text def draw(self, win, outline=None): # 绘制按钮到窗口 if outline: pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0) pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0) if self.text != '': font = pygame.font.SysFont('comicsans', 60) text = font.render(self.text, 1, (0, 0, 0)) win.blit(text, ( self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2) )) def isOver(self, pos): # 判断传入的坐标是否在按钮范围内 if self.x < pos[0] < self.x + self.width: if self.y < pos[1] < self.y + self.height: return True return False # 初始化Pygame并创建窗口 pygame.init() WIN = pygame.display.set_mode((800, 600)) # 窗口大小可自行调整 bg = pygame.Surface((800, 600)) bg.fill((100, 100, 100)) # 设置背景色,可自行调整 one = button((255,255,255),250,500, 90,90 ,'hi') def DRAW_WINDOW(): WIN.blit(bg,(0,0)) one.draw(WIN, (0,0,0)) pygame.display.update() def main(): run = True while run: for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: pos = event.pos # 获取鼠标移动时的坐标 if one.isOver(pos): one.color = (255,0,0) else: one.color = (255,255,255) if event.type == pygame.MOUSEBUTTONDOWN: pos = event.pos # 获取鼠标点击时的坐标 if one.isOver(pos): print('ow') if event.type == pygame.QUIT: run = False DRAW_WINDOW() if __name__ == "__main__": main() pygame.quit()
内容的提问来源于stack exchange,提问作者Fantom
相关产品推荐
相关产品推荐

