简体   繁体   English

如何在python中每次将项目附加到列表中

[英]How to append items to a list one time each in python

Lets say I have a list called my_list and a function called my_function and my_function appends items to my_list based on which portion of the surface gameDisplay was clicked on.假设我有一个名为 my_list 的列表和一个名为 my_function 的函数,my_function 根据点击了表面 gameDisplay 的哪个部分将项目附加到 my_list。 However whenever you hold down the mouse for more than one frame, it appends more than one of that item to my_list.但是,只要您按住鼠标超过一帧,它就会将多个该项目附加到 my_list。 This is not the result I am going for.这不是我想要的结果。 I was wondering if there was a way you could do this without appending more than one of each item to my_list我想知道是否有一种方法可以在不将每个项目中的一个以上附加到 my_list 的情况下执行此操作

Thanks for your help谢谢你的帮助

You didn't show code but I guess you use pygame.mouse.get_pressed() which gives True all the time when you keep button pressed.您没有显示代码,但我猜您使用的是pygame.mouse.get_pressed() ,当您按住按钮时,它始终提供True And this can be your problem.这可能是你的问题。

You can do one of two things:您可以执行以下两项操作之一:

use event.MOUSEBUTTONDOWN which is created only once - when button change state from not-pressed into pressed .使用event.MOUSEBUTTONDOWN其中创建只有一次-从当按钮改变状态not-pressedpressed

Or:或者:

use extra variable which will remeber pygame.mouse.get_pressed() from previous frame.使用额外的变量来pygame.mouse.get_pressed()前一帧的pygame.mouse.get_pressed() And then compare if now button is pressed but in previous frame was not-pressed then add element to list.然后比较是否按下了现在按钮但在前一帧中未按下,然后将元素添加到列表中。


EDIT: old code from different question which use event.MOUSEBUTTONDOWN to change color.编辑:来自不同问题的旧代码,它使用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 GitHub: furas/python-examples/pygame/button-click-cycle-color

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM