PySimpleGUI - Tree Element



A Tree is a hierarchical data structure consisting of one or more nodes, and each node may have one or more children nodes. This arrangement of nodes is done in an object of TreeData object, which is used as a data parameter for creating a Table.

First of all, declare a TreeData object.

treedata = psg.TreeData()

Use the insert() method of the TreeData class to construct the hierarchy of nodes.

TreeData.insert(parent_key, key, display_text, values)

To insert a node at the first level of the tree, use the parant_key as "". So, every top-level node in the tree will have a parent node = "". To insert a child node, give the key of the node at the upper level as its parent_key.

For example,

insert("","MH", "Maharashtra", (175, 150, 200))

will insert a node at the root level with MH as the key.

On the other hand, the following command

insert("MH", "MUM", "Mumbai", (100, 100,100))

will insert a child node with its key as MUM.

The TreeData object is used to construct a Tree object with following parameters −

Sr.No. Parameter & Description
1 data

The data represented using TreeData class

2 headings

List of individual headings for each column

3 col_widths

List of column widths for individual columns

4 col0_width

Size of Column 0

5 col0_heading

Text to be shown in the header for the left-most column

6 def_col_width

Default column width

7 auto_size_columns

If True, the size of a column is determined by contents of the column

8 select_mode

Same as Table Element

9 show_expanded

If True, the tree will be initially shown with all nodes completely expanded

In the following example, we display a statewise list of cities in a tree structure

import PySimpleGUI as psg
psg.set_options(font=("Arial Bold",14))
treedata = psg.TreeData()
rootnodes=[
   ["","MH", "Maharashtra", 175, 150, 200],
   ["MH", "MUM", "Mumbai", 100, 100,100],
   ["MH", "PUN", "Pune", 30, 20, 40],
   ["MH", "NGP", "Nagpur", 45, 30, 60],
   ["","TEL", "Telangana", 120, 80, 125],
   ["TEL", "HYD", "Hyderabad", 75, 55, 80],
   ["TEL", "SEC", "Secunderabad", 25, 15, 30],
   ["TEL", "NZB", "Nizamabad", 20, 10, 15]
]
for row in rootnodes:
   treedata.Insert( row[0], row[1], row[2], row[3:])
tree=psg.Tree(data=treedata,
   headings=['Product A','Product B','Product C' ],
   auto_size_columns=True,
   select_mode=psg.TABLE_SELECT_MODE_EXTENDED,
   num_rows=10,
   col0_width=5,
   key='-TREE-',
   show_expanded=False,
   enable_events=True,
   expand_x=True,
   expand_y=True,
)
layout=[[tree]]
window=psg.Window("Tree Demo", layout, size=(715, 200), resizable=True)
while True:
   event, values = window.read()
   print ("event:",event, "values:",values)
   if event == psg.WIN_CLOSED:
      break

It will produce the following output window −

Tree Element
pysimplegui_element_class.htm
Advertisements