开发者

Remove item in a Python kiwi objectlist

I have an generic example from kiwi framework, my question is: How can I remove only a item from kiwi objectlist.

Thanks for the time!

import gtk

from kiwi.ui.objectlist import Column, ObjectList

class Fruit:
    def __init__(self, name, cost):
        self.name = name
        self.cost = cost

fruits = ObjectList([Column('name', data_type=str, editable=True,
                      expand=True),
               Column('cost', data_type=int, editable=True)])

for name, cost in [('Apple', 4),
                   ('Pineapple', 2),
                   ('Kiwi', 8),
                   ('Banana', 3),
                   ('Melon', 5)]:
    fruits.append(Fruit(name, cost))

window = gtk.Window()
window.connect('delete-event', gtk.main_quit)
window.set_title('Editable Fruit List')
window.set_size_request(230, 150)

#
## remove fruits
#
fruits开发者_Go百科.remove(Fruit('Pineapple', 4))  #error

window.add(fruits)
window.show_all()

gtk.main()


This code:

fruits.remove(Fruit('Pineapple', 4))  

produces this error:

Traceback (most recent call last):
...
    fruits.remove(Fruit('Pineapple', 4))  #error
  File "/tmp/kiwi/ui/objectlist.py", line 1651, in remove
    raise ValueError("instance %r is not in the list" % instance)
ValueError: instance <__main__.Fruit instance at 0x90066cc> is not in the list

which is an accurate description of the problem.


The instance argument to the .remove method of an ObjectList should be an object already in the list. Whenever you call Fruit(...) you get a new instance ever it its attributes are the same. If the instance is not in the list, a ValueError is raised (despite what the documentation says, apparently). For example:

new_fruit = Fruit('Pineapple', 4) # save this instance as new_fruit
fruits.append(new_fruit) # append this instance to the list
fruits.remove(new_fruit) # take this instance out ... success!

assert new_fruit is Fruit('Pineapple', 4) # False

So, in your existing code, you'll probably want to do something like this instead (replacing fruits.remove(Fruit('Pineapple', 4))):

fruits.remove(fruits[1])

Or, tie it to some ui action (double-click is just an example):

def remove_fruit(objlist, instance):
    objlist.remove(instance)

fruits.connect('double-click', remove_fruit)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜