【问题标题】:set behaves unexpectedly in a python classset 在 python 类中的行为异常
【发布时间】:2015-07-01 17:16:30
【问题描述】:

我有一些对象,比如画布上的矩形,并且我想要为每个对象设置一个集合,其中包含其相邻单元格的 id

这是该类的代码,idC 是我感兴趣的 id,它们由 Tkinter 的 create_rectangle 函数分配给每个单元格

class Cell(Rectangle):
    def __init__(self, canvas, row, column):
        # make a 10x10 rectangle in the given row, column
        x0 = column * 10
        y0 = row * 10
        x1 = x0 + 10
        y1 = y0 + 10         

        super(Cell, self).__init__(canvas, (x0, y0, x1, y1), "white")

        self.get_neighbours()


    state = 'dead'
    neighbours = set()
    border = set()

    def get_neighbours(self):

        if self.idC % 95 == 1: self.border.add('left')  #the numbers are like so because my canvas is 950x950
        if self.idC % 95 == 0: self.border.add('right')
        if self.idC < 96: self.border.add('top')
        if self.idC > 8930: self.border.add('bottom')
        if 'left' not in self.border: self.neighbours.add(self.idC - 1)
        if 'right' not in self.border:self.neighbours.add(self.idC + 1)
        if 'top' not in self.border:
            if 'left' not in self.border:self.neighbours.add(self.idC - 94)
            self.neighbours.add(self.idC - 95)
            if 'right' not in self.border:self.neighbours.add(self.idC - 96)
        if 'bottom' not in self.border:
            if 'left' not in self.border:self.neighbours.add(self.idC + 94)
            self.neighbours.add(self.idC + 95)
            if 'right' not in self.border:self.neighbours.add(self.idC + 96)

    def change_state(self):
        self.state = 'alive' if self.state == 'dead' else 'dead'
        color = "black" if self.state == "alive" else "white"
        print(self.idC)
        print("neighbours:")
        #print(self.neighbours)
        print(len(self.neighbours))
        if not GameOfLife.running: self.canvas.itemconfigure(self.idC, fill=color) 

这是我如何使用其他小部件在另一个类中创建所有单元格的方法:

    for i in range(95):
        for p in range(95):
            self.organism.append(Cell(c, i, p))

    for cell in self.organism:            
        c.tag_bind(cell.idC, '<ButtonPress-1>', lambda _, x = cell: x.change_state())

发生的情况是所有 id 都被添加到集合 neighbours 中,但触发函数的 ID 除外;其他一切都可以正常工作 - 点击一个单元格会正确打印其 id

这一定是一些新手的错误,但我不知道出了什么问题..

更新:我发现每个单元格也被标记为在画布上的所有边框上,所以它必须是当函数被一次又一次调用时,它会将所有 ID 添加到同一个集合中,而不是制作不同的为类的每个实例设置。我尝试从不同的地方调用它,但我仍然得到相同的结果......

【问题讨论】:

  • 问题是你的关闭,在最后一个sn-p:docs.python-guide.org/en/latest/writing/gotchas/…
  • @DanielRoseman 但我想我已经用x = cell 部分解决了这个问题......当change_state() 被触发时,无论我点击哪里,最后一个单元格都出现了这个问题,现在它没有不要再这样做了;现在所有不同的 id 都被添加到集合中,长度为 95^2 - 1
  • 啊,你是对的,对不起;我看错了代码。
  • 抱歉,最后一个代码块中的c 是什么?
  • @dbliss c 是我所谓的画布,也许我应该把它说得更清楚

标签: python class tkinter


【解决方案1】:

好的,所以我将整个 get_neighbours() 以及与之关联的所有变量都移到了父类中,现在它可以正常工作了

我仍然不知道它为什么会这样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2018-03-26
    • 1970-01-01
    相关资源
    最近更新 更多