高级Python GUI工具包,例如,将字典传递给TreeView/Grid

5 投票
4 回答
3087 浏览
提问于 2025-04-16 00:32

我开始了我的第一个Python小项目,使用的是PyGTK。虽然这个图形界面工具包非常强大,效果也很好,但我还是有一些小烦恼。所以我考虑换个工具,因为现在还不算太复杂。我在StackOverflowPython文档上转了一圈,但没有找到一个好的概述。

关于PyGTK,有几个不错的地方:

  • 可以使用Glade文件
  • 可以用self.signal_autoconnect({...})来自动连接信号
  • 可以用self.get_widget()来获取小部件,像是__getattr__一样

不过,有一些让我烦恼的地方:

  • 需要手动使用gobject.idle_add(lambda: ... 和 False)
  • 没有标准功能来保存应用程序或窗口的状态
  • TreeView需要手动构建数组
  • widget.get_selection().get_selected()和model.get_value(iter, liststore_index)

TreeView:因为这是主要的界面元素,所以最让人分心。基本上,我的应用程序需要构建一个字典列表来显示,格式是name=列+行=>值。要在GTK中显示这些内容,需要手动转换、排序和类型转换。这感觉有点繁琐,我希望能有更面向对象的方式。PyGTK在gtk+之上有很多抽象,但看起来还是比较底层。我希望能直接传递我的字典,并且能够以某种方式预定义列。(GtkBuilder可以预定义TreeView的列,但这并没有解决数据表示的繁琐问题。)

当我在TreeView列表上点击鼠标时,我还需要把所有东西转换回我的应用程序数据结构。而且,PyGTK在非主线程中运行时,并没有自动处理gtk+的调用,这让我觉得很烦。目前有很多GUI代码,我觉得这些代码其实不应该是必要的,或者可以简化。

? 那么,是否有其他的包装工具在PyGTK之上?或者还有哪些工具包支持更简单的网格/树视图显示接口。我听说wxPython是大家的最爱,但在Linux上不够成熟。而PyQT似乎和PyGTK的抽象层次差不多。我对TkInter了解不多,不知道它是否有更简单的接口,但看起来不太吸引人。PyFLTK也是如此。PyJamas听起来很有趣,但已经太远了(桌面应用程序)。

.

所以,图形界面工具包要能把字典显示为网格。你会选择哪个呢?

.

作为例子,这是我当前的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 个回答

3
4

我之前没听说过Kiwi。谢谢你,Johannes Sasongko。

这里有一些我收藏的工具包。这些工具包中,有些是其他工具包(比如GTK、wxWidgets)的封装,而有些则是独立的:

(我列出了一些已经提到过的工具包,以便其他看到这个帖子的人参考。我本来想把这个作为评论发的,但内容有点长。)

5

可以试试Kiwi,也许会有帮助?特别是它的ObjectList功能。

更新:我觉得Kiwi的开发已经转移到PyGTKHelpers了。

撰写回答