gpt4 book ai didi

python - 我无法使类方法起作用;如果我将方法代码复制粘贴到应该调用该方法的位置,它就可以工作

转载 作者:行者123 更新时间:2023-12-04 15:11:45 27 4
gpt4 key购买 nike

在使用 Python 编写自己的类时,我还比较陌生。我在一个程序中工作,在这个程序中我已经定义了 3 个类,每个类有 4/5 个方法,每个类都可以正常工作。但是我在一个小时内遇到了一个新问题,我无法弄清楚我做错了什么。事实上,即使没有弹出错误消息,该方法也不起作用,但如果我在我的 pygame 循环(调用它的地方)中复制粘贴该方法的代码,它就可以正常工作。这是我类(class)的代码(.click(self) 方法是这里的关键之一):

class button:
def __init__(self, window, xpos, ypos, width, height, color = white, text = '', dest = None):
self.xpos = xpos * r
self.ypos = ypos * r
self.width = width * r
self.height = height * r
self.color = color
self.colorBuffer = [color[i] for i in range(3)]
self.window = window
self.hovered = False
self.clicked = False
self.text = text
self.dest = dest
#self.R = color[0]
#self.G = color[1]
#self.B = color[2]

def click(self):
self.clicked = True
if self.dest == None:
pass
else:
currentMenu = self.dest
self.dest.disp()
self.clicked = False

这是调用方法的代码(当程序检查 event.type == MOUSEBUTTONDOWN 时调用):

loop = False
if loop == False:
currentMenu = mainMenu
loop = True
boxisinputting = False
boxinputting = None
userisinputting = False

while loop == True:
pygame.display.flip()
userisinputting = False
mousex, mousey = pygame.mouse.get_pos()
currentMenu.disp()
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if pygame.key.name(event.key) == 'return':
boxinputting.inputting = False
boxisinputting = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
for but in currentMenu.buttonList:
if but.hovered == True:
but.click()
if boxisinputting == False:
for box in currentMenu.inputBoxList:
if box.hovered == True:
box.inputting = True
boxisinputting = True
boxinputting = box
if userisinputting == True:
boxinputting.render()
pygame.time.delay(100)

当我运行这段代码时会发生什么:下一个菜单显示正常,但它的按钮没有响应(无论鼠标是否在按钮上,我都有点亮或熄灭它的方法);相反,当我将指针移到它们所在的位置时,弹出的是上一个菜单的按钮。但是,当我复制粘贴指令时,我希望我的方法 .click(self) 在这里执行:

if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
for but in currentMenu.buttonList:
if but.hovered == True:
but.clicked = True
if but.dest == None:
pass
else:
currentMenu = None
currentMenu = but.dest
but.dest.disp()
but.clicked = False

... 好吧,它工作得非常好:按钮处于事件状态并且有响应,并且之前的按钮不会凭空弹出(这是我愿意做的)。我可以摆脱它,因为这只会在我的循环中浪费 5 或 6 行。但我很想知道为什么我无法使该方法起作用,以避免将来出现此类问题。

感谢您阅读我的帖子!

威廉

最佳答案

这很难说,因为包含的代码没有显示 button 的实例化,但您可能需要确保它引用了全局范围:

def click(self):
global currentMenu, gamesMenu
currentMenu = gamesMenu
print('click')

如果它只是一个按钮,您的按钮类会更好。所以这与位置、标签、颜色、是否被点击、未点击、悬停等有关。但不是也很重要。按钮不是菜单,它不应该知道菜单,也不应该处理菜单(或刷新显示缓冲区!)。

当对象的行为简洁明了时,它们会产生更好的设计和更清晰的代码。

关于python - 我无法使类方法起作用;如果我将方法代码复制粘贴到应该调用该方法的位置,它就可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65098860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com