【问题标题】:How to append items to a list one time each in python如何在python中每次将项目附加到列表中
【发布时间】:2017-01-14 22:34:00
【问题描述】:

假设我有一个名为 my_list 的列表和一个名为 my_function 的函数,my_function 根据点击了表面 gameDisplay 的哪个部分将项目附加到 my_list。但是,只要您按住鼠标超过一帧,它就会将该项目中的多个附加到 my_list。这不是我想要的结果。我想知道是否有一种方法可以做到这一点,而无需将多个项目附加到 my_list

感谢您的帮助

【问题讨论】:

  • 向我们展示您的代码。
  • 你的代码在哪里?
  • 也许你可以使用set()
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误在问题本身中重现它所需的最短代码。没有明确的问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable Example

标签: python arrays pygame append


【解决方案1】:

您没有显示代码,但我猜您使用pygame.mouse.get_pressed(),当您按住按钮时,它始终提供True。这可能是您的问题。

你可以做以下两件事之一:

使用仅创建一次的event.MOUSEBUTTONDOWN - 当按钮将状态从not-pressed 更改为pressed 时。

或者:

使用额外的变量,它将从前一帧中记住 pygame.mouse.get_pressed()。然后比较是否按下了现在按钮但在前一帧中没有按下然后将元素添加到列表中。


编辑: 来自不同问题的旧代码,使用event.MOUSEBUTTONDOWN 更改颜色。

#!/usr/bin/env python

# http://stackoverflow.com/questions/33856739/how-to-cycle-3-images-on-a-rect-button

import pygame

# - init -

pygame.init()
screen = pygame.display.set_mode((300,200))

# - objects -

# create three images with different colors
images = [
    pygame.Surface((100,100)),    
    pygame.Surface((100,100)),    
    pygame.Surface((100,100)),    
]    

images[0].fill((255,0,0))
images[1].fill((0,255,0))
images[2].fill((0,0,255))

images_rect = images[0].get_rect()

# choose first image
index = 0

# - mainloop -

running = True

while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:

            if event.button == 1 and images_rect.collidepoint(event.pos):
                # cycle index
                index = (index+1) % 3

    # - draws -

    screen.blit(images[index], images_rect)
    pygame.display.flip()

# - end -

pygame.quit()

GitHub:furas/python-examples/pygame/button-click-cycle-color

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2013-08-07
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多