【问题标题】:iterating through a list with self parameter使用 self 参数遍历列表
【发布时间】:2016-04-26 21:41:43
【问题描述】:

尝试遍历包含矩形的列表。然后从列表中删除/删除所有橙色的矩形。我为它写了一段代码,但不断收到不可迭代的错误。

from tkinter import *
import random
root = Tk()
from Stack import Stack
from my_queue import *

class Recta:

  def __init__(self, height=60, width=80 ,colours= []):
    self.height = height
    self.width = width
    self.canvas = Canvas(root)
    self.canvas.pack()
    self.colours = ["red", "orange"]
    self.rects = []
    self.stack = Stack()
    self.queue = Queue()

  def randomRects(self):
    w = random.randrange(300)
    h = random.randrange(200)
    self.rects.append(self.canvas.create_rectangle(0, 0, w, h, fill= random.choice(self.colours)))

  def remove_all_orange_shapes(self):
    for i in self.randomRects():
        if i == "orange": 
          return self.canvas.delete(self.rects.pop())
        else:
          continue 

tes = Recta()
tes= Stack()
tes = Queue()
root.mainloop()

【问题讨论】:

  • randomRects 返回None ... 所以粗略的for item in None 是无效的python
  • 你说出三个对象tes?
  • @PadraicCunningham ...但继续不使用它们...
  • @JoranBeasley,是的,更值得深思。
  • @rprogramr,我建议你阅读教程anandology.com/python-practice-book

标签: python list class python-3.x


【解决方案1】:

randomRects 正在创建一个矩形列表,但它不是返回一个矩形列表。它返回默认返回值None。当您尝试迭代它 (for i in self.randomRects()) 时,您正在迭代值 None,这将引发错误。

第二个问题是self.rects 正在创建一个画布对象 id 列表,但您将这些 id 与字符串“orange”进行比较,这永远不会是真的。画布对象 ID 是数字。

您需要做的是 a) 循环 self.rects,并且 b) 在进行比较之前获取项目的颜色。然后,c) 删除画布项,d) 更新self.rects

有几种方法可以做到这一点。以下是一种方式。不过,它假设您已经提前创建了随机矩形。您的代码的工作方式是同时创建和删除所有矩形。

def remove_all_orange_shapes(self):
    new_rects = []
    for i in self.rects:
        color = self.canvas.itemcget(i, "fill")
        if color == "orange": 
            # delete the orange ones ...
            self.canvas.delete(i)
        else:
            # ... and save the non-orange ones
            new_rects.append(i)
    self.rects = new_rects

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多