更高级别的Python GUI工具包,例如传递TreeView / Grid的dict

时间:2010-06-28 21:06:46

标签: python user-interface gtk pygtk

使用PyGTK开始我的第一个Python宠物项目。虽然它是一个非常强大的GUI工具包,看起来很棒,但我有一些小小的烦恼。所以我考虑过渡到别的东西,因为它还不是太广泛。看了SOpython documentation,但没有得到很好的概述。

PyGTK有什么好处:

  • Glade文件
  • self.signal_autoconnect({...})
  • self.get_widget()as __getattr __

然而,这让我烦恼:

  • manual gobject.idle_add(lambda:... and False)
  • 没有用于保存应用程序/窗口状态的标准功能
  • TreeView需要构建数组
  • widget.get_selection()。get_selected(),model.get_value(iter,liststore_index)

TreeView :因为这是主界面元素,所以它最让人分心。基本上我的应用程序构建了一个要显示的字典列表name = column + row => value。要使用GTK显示它,需要手动转换过程,订购,类型转换。这似乎是很多开销,我希望在这里有一些更面向对象的东西。 PyGtk在gtk +之上有许多抽象,但仍然看起来相当低级。我更喜欢按原样传递我的字典,并以某种方式预定义列。 (GtkBuilder可以预定义TreeView列,但这不能解决数据表示开销。)

当我在TreeView列表上看到mousclick时,我还必须将所有内容转换回我的应用程序数据结构。而且,如果从非主线程运行,PyGTK不会使用gobject.idle本身包装gtk +调用也很令人讨厌。现在有很多GUI代码我认为不应该是必要的,或者可以合理化。

那么,PyGTK上是否还有其他包装器。或者哪个其他工具包支持更简单的界面来显示Grid / TreeView。我已经阅读了很多关于wxPython是每个人最喜欢的东西,但它在Linux上不太成熟。并且 PyQT 似乎与PyGTK大致相同的抽象级别。没有使用 TkInter ,所以不知道它是否有更简单的接口,但它无论如何看起来没有吸引力。和 PyFLTK 一样。睡衣听起来很迷人,但已经太过分了(桌面应用程序)。

所以,带有dict的GUI工具包 - >网格显示。你会选哪个?

就像展出的那样,这是我当前的TreeView映射功能。一些作品,但我宁愿有一些标准的东西:

    #-- fill a treeview
    #
    # Adds treeviewcolumns/cellrenderers and liststore from a data dictionary.
    # Its datamap and the table contents can be supplied in one or two steps.
    # When new data gets applied, the columns aren't recreated.
    #
    # The columns are created according to the datamap, which describes cell
    # mapping and layout. Columns can have multiple cellrenderers, but usually
    # there is a direct mapping to a data source key from entries.
    #
    # datamap = [  #  title   width    dict-key    type,  renderer,  attrs  
    #               ["Name",   150,  ["titlerow",   str,    "text",    {} ]  ],
    #               [False,     0,   ["interndat",  int,     None,     {} ]  ],
    #               ["Desc",   200,  ["descriptn",  str,    "text",    {} ],  ["icon",str,"pixbuf",{}]  ],
    #
    # An according entries list then would contain a dictionary for each row:
    #   entries = [ {"titlerow":"first", "interndat":123}, {"titlerow":"..."}, ]
    # Keys not mentioned in the datamap get ignored, and defaults are applied
    # for missing cols. All values must already be in the correct type however.
    #
    @staticmethod
    def columns(widget, datamap=[], entries=[], pix_entry=False):

        # create treeviewcolumns?
        if (not widget.get_column(0)):
            # loop through titles
            datapos = 0
            for n_col,desc in enumerate(datamap):

                # check for title
                if (type(desc[0]) != str):
                    datapos += 1  # if there is none, this is just an undisplayed data column
                    continue
                # new tvcolumn
                col = gtk.TreeViewColumn(desc[0])  # title
                col.set_resizable(True)
                # width
                if (desc[1] > 0):
                    col.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
                    col.set_fixed_width(desc[1])

                # loop through cells
                for var in xrange(2, len(desc)):
                    cell = desc[var]
                    # cell renderer
                    if (cell[2] == "pixbuf"):
                        rend = gtk.CellRendererPixbuf()  # img cell
                        if (cell[1] == str):
                            cell[3]["stock_id"] = datapos  # for stock icons
                            expand = False
                        else:
                            pix_entry = datapos
                            cell[3]["pixbuf"] = datapos
                    else:
                        rend = gtk.CellRendererText()    # text cell
                        cell[3]["text"] = datapos
                        col.set_sort_column_id(datapos)  # only on textual cells

                    # attach cell to column
                    col.pack_end(rend, expand=cell[3].get("expand",True))
                    # apply attributes
                    for attr,val in cell[3].iteritems():
                        col.add_attribute(rend, attr, val)
                    # next
                    datapos += 1

                # add column to treeview
                widget.append_column(col)
            # finalize widget
            widget.set_search_column(2)   #??
            widget.set_reorderable(True)

        # add data?
        if (entries):
            #- expand datamap            
            vartypes = []  #(str, str, bool, str, int, int, gtk.gdk.Pixbuf, str, int)
            rowmap = []    #["title", "desc", "bookmarked", "name", "count", "max", "img", ...]
            if (not rowmap):
                for desc in datamap:
                    for var in xrange(2, len(desc)):
                        vartypes.append(desc[var][3])  # content types
                        rowmap.append(desc[var][0])    # dict{} column keys in entries[] list
            # create gtk array storage
            ls = gtk.ListStore(*vartypes)   # could be a TreeStore, too

            # prepare for missing values, and special variable types
            defaults = {
                str: "",
                unicode: u"",
                bool: False,
                int: 0,
                gtk.gdk.Pixbuf: gtk.gdk.pixbuf_new_from_data("\0\0\0\0",gtk.gdk.COLORSPACE_RGB,True,8,1,1,4)
            }
            if gtk.gdk.Pixbuf in vartypes:
                pix_entry = vartypes.index(gtk.gdk.Pixbuf) 

            # sort data into gtk liststore array
            for row in entries:
                # generate ordered list from dictionary, using rowmap association
                row = [   row.get( skey , defaults[vartypes[i]] )   for i,skey   in enumerate(rowmap)   ]

                # autotransform string -> gtk image object
                if (pix_entry and type(row[pix_entry]) == str):
                    row[pix_entry] = gtk.gdk.pixbuf_new_from_file(row[pix_entry])

                # add
                ls.append(row)   # had to be adapted for real TreeStore (would require additional input for grouping/level/parents)

            # apply array to widget
            widget.set_model(ls)
            return ls

        pass

4 个答案:

答案 0 :(得分:5)

尝试Kiwi,也许吧?尤其是ObjectList

更新:我认为新西兰的发展已经转移到PyGTKHelpers

答案 1 :(得分:4)

我之前没有遇到过新西兰人。谢谢,Johannes Sasongko。

以下是我保留书签的更多关注点。其中一些是围绕其他工具包(GTK,wxWidgets)的包装器,而其他工具包是独立的:

(我已经包含了一些为了遇到这篇文章而被提及的人。我会把它作为评论发布,但是有点太长了。)

答案 2 :(得分:3)

答案 3 :(得分:1)

I would suggest taking a look at wxPython。虽然我不得不承认我自己没有对Treeviews做过很多事情,但我发现它很容易上手并且非常强大。

wxWidgets将等效控件称为wxTreeCtrl

[编辑] wxDataViewTreeCtrl实际上可能更适用于您的情况。