【问题标题】:If else statement append to list in for loopif else 语句追加到 for 循环中的列表
【发布时间】:2020-08-26 05:45:15
【问题描述】:

我想将海龟 'person' 添加到列表 'infected_people' 中,但我收到错误消息 'TurtleGraphicsError: bad color string: red'。

如何将“人”添加到列表“受感染的人”中而不会出现错误。

如果我的解释不清楚,我是编程新手,很抱歉。


infected_people = []

i = 0
while i < 30: #number of steps (time)
  for person in people: 
      random_walk(30, 400)
      i + 1
      for infected_person in infected_people: 
          if person.distance(infected_person) < 30: 
              person.color("red")
              infected_people.append(person) 


这是我的代码的另一部分:

import turtle
import random

wn = turtle.Screen()

def person_characteristics(): 
    for person in people:
        person.penup()
        person.shape("circle")
        person.shapesize(0.2)
        x = random.randint(-200, 200)
        y = random.randint(-200, 200)
        person.setpos(x, y)
        person.speed(0)
        turtle.update()
    return person


def population(population_size):
    turtle.update()
    people = []
    for _ in range(population_size):
        people.append(turtle.Turtle())
    return people

def person_characteristics(): 
    for person in people:
        turtle.update()
        person.penup()
        person.shape("circle")
        person.shapesize(0.2)
        person.speed(0)
        x = random.randint(-200, 200)
        y = random.randint(-200, 200)
        person.setpos(x, y)
    return person

def random_walk(step_size, area_size):
    person.clear()
    count = 0
    while count < 1:
        count += 1
        if (-area_size < person.xcor() <area_size) and (-area_size < person.ycor() <area_size):
            person.right(random.randint(0,360))
            person.forward(step_size)
        else:
            person.right(180)
            person.forward(step_size)
    turtle.update()

people = population(50)
person = person_characteristics()

def infect_random(people):
    infected = random.choice(people)
    infected.color("red")
    return infected

infected_people = []
initial_infected = infect_random(people)
infected_people.append(initial_infected)
print(infected_people)
counted_infections = 0

我的目标是每个被感染的人(= 红点)感染每个靠近他的人。现在只有最初的感染者会感染其他人。所以我想如果我将每个被感染的人都添加到受感染的人列表中,那么它会起作用。但是,当添加受感染的人.append(person) 行时出现错误。

i = 0
while i < 30: #number of steps (time)
    for person in people: 
        random_walk(30, 400)
        i += 1
        for infected_person in infected_people: 
            if person.distance(infected_person) < 30: 
                person.color("red")
                infected_people.append(person)



turtle.done()
wn.exitonclick()

这是我得到的错误:

runfile('C:/Users/Noa Hoogeweg/Documents/BMT/PvL/Virus/Noa_Virus_goed.py', wdir='C:/Users/Noa Hoogeweg/Documents/BMT/PvL/Virus')
[<turtle.Turtle object at 0x000001FF4D3D9908>]
Traceback (most recent call last):

  File "C:\Users\Noa Hoogeweg\Documents\BMT\PvL\Virus\Noa_Virus_goed.py", line 78, in <module>
    person.color("red")

  File "C:\Users\Noa Hoogeweg\anaconda3\lib\turtle.py", line 2216, in color
    pcolor = self._colorstr(pcolor)

  File "C:\Users\Noa Hoogeweg\anaconda3\lib\turtle.py", line 2696, in _colorstr
    return self.screen._colorstr(args)

  File "C:\Users\Noa Hoogeweg\anaconda3\lib\turtle.py", line 1158, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))

TurtleGraphicsError: bad color string: red

【问题讨论】:

  • 能否将您收到的输入和错误添加到您的问题中?
  • 如果您将 rgb 值作为 `color(r,g,b)` 传递,是否会出现同样的错误?

标签: python list for-loop if-statement turtle-graphics


【解决方案1】:

我不知道您遇到了什么错误,但i + 1 行不会增加 i,要增加 i 的值,您需要使用 i = i + 1i += 1

【讨论】:

    【解决方案2】:

    您对person.color("red") 的调用看起来完全有效,我在运行代码时没有收到错误消息。

    根据你的错误堆栈跟踪,turtle 只对你的颜色字符串做两件事。首先,它测试它是否是str——你必须通过该测试才能得到你得到的错误。其次,它将颜色字符串传递给 tkinter 的 winfo_rgb() 方法,该方法返回一个 RGB 三元组。 Turtle 忽略了三元组,它只是想看看那个函数是成功还是抛出错误。如果它抛出一个错误,你会得到你显示的消息:

    TurtleGraphicsError: bad color string: red
    

    所以球在 tkinter 的球场上,试试下面的小程序,看看 tkinter 是否做对了你:

    from tkinter import Button
    
    # Button is an arbitrary widget choice
    print(Button().winfo_rgb("red"))
    

    如果它有效,你应该得到类似的东西:

    > python3 test.py
    (65535, 0, 0)
    >
    

    在这种情况下,您的海龟代码与 tkinter 库挂钩的方式存在可疑之处。如果上述失败,你应该得到类似的东西:

    > python3 test.py
    Traceback (most recent call last):
      File "test.py", line 4, in <module>
        print(Button().winfo_rgb("red"))
      File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1156, in winfo_rgb
        self.tk.call('winfo', 'rgb', self._w, color))
    _tkinter.TclError: unknown color name "red"
    >
    

    在这种情况下,您可能需要检查 tkinter 安装的有效性。

    即使您修复了"red" 问题,您的代码中仍有其他错误会导致其无法正常工作。以下是我为使其正常运行而进行的重写:

    from turtle import Screen, Turtle
    from random import randint, choice
    
    def person_characteristics(people):
        for person in people:
            person.shape('circle')
            person.shapesize(0.2)
            person.speed('fastest')
            person.penup()
            x = randint(-200, 200)
            y = randint(-200, 200)
            person.setpos(x, y)
            person.showturtle()
    
    def population(population_size):
        people = []
    
        for _ in range(population_size):
            people.append(Turtle(visible=False))
    
        return people
    
    def random_walk(person, step_size, area_size):
        if -area_size < person.xcor() < area_size and -area_size < person.ycor() < area_size:
            person.right(randint(0, 360))
            person.forward(step_size)
        else:
            person.right(180)
            person.forward(step_size)
    
    def infect_random(people):
        infected = choice(people)
        infected.color('red')
        return infected
    
    screen = Screen()
    
    people = population(50)
    person_characteristics(people)
    
    infected_people = []
    initial_infected = infect_random(people)
    infected_people.append(initial_infected)
    
    counted_infections = 1
    
    for _ in range(3000): # number of steps (time)
        for person in people:
            random_walk(person, 30, 400)
    
            for infected_person in infected_people:
                if person.pencolor() != 'red' and person.distance(infected_person) < 30:
                    person.color('red')
                    infected_people.append(person)
                    break
    
    screen.exitonclick()
    

    【讨论】:

      猜你喜欢
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多