- How to set width of Treeview in tkinter of python
- How to change ttk.Treeview column width and weight in Python 3.3?
- Example
- Output
- Treeview¶
- Multiple columns¶
- Configure style¶
- Bind to events¶
- Two treeviews next to each other¶
- Display a 2D table¶
- Insert items into a treeview¶
- Add items to specific column¶
- Customize the treeview widget¶
How to set width of Treeview in tkinter of python
It’s possible to achieve this using the place geometry manager. Although not highly recommended, the place manager lets you specify the width of the widget:
tree_view = ttk.Treeview(root) tree_view.place(relx=0.01, rely=0.1, width=500, height=500)
After trying so many ways to solve this problem, I find out a simple but silly solution. After initializing the width of the Treeview , you just need to resize the with of the column and the width of the Treeview will NOT change.
Perhaps, this is the constraint of Tcl/Tk.
After searching for over a week now, I stumbled upon a very easy way to do the ‘magic’.
- I read the current size of my mainWindow
- Add the data to the treeView
- Set the width of each column depending on the max length of an entry (by using measure )
- Calling the update function on my mainWindow (not sure if this is needed)
- Setting the size of the mainWindow to the stored values
def reloadTreeViewData(self): # get current size of main window curMainWindowHeight = self.parent.winfo_height() curMainWindowWidth = self.parent.winfo_width() #delete all for child in self.tree.get_children(): self.dicData = <> self.tree.delete(child) # reload all count = 0 for row in self.data: adding_string = [] for element in self.indexlist: adding_string.append(str(row[element])) insert_ID = self.tree.insert('', 'end', text=count, values=adding_string) # save the data in it's original types in a dictionary self.dicData[insert_ID] = [row[x] for x in self.indexlist] count += 1 # reset column width max_colum_widths = [0] * len(self.indexlist) for child in self.tree.get_children(): rowData = self.dicData[child] for idx, rowIdx in enumerate(self.indexlist): item = rowData[idx] new_length = self.myFont.measure(str(item)) if new_length > max_colum_widths[idx]: max_colum_widths[idx] = new_length for idx, item in enumerate(self.attributeList): if int(max_colum_widths[idx]) < 50: self.tree.column(item, width=50) else: self.tree.column(item, width=int(max_colum_widths[idx])) # restore the size of the mainWindow self.parent.update() self.parent.geometry("" + str(curMainWindowWidth) + "x" + str(curMainWindowHeight))
My headings for the treeView are stored in self.attributeList but the data comes from a database, which has way more columns I want to show. So I use a mapping list which is stored as self.indexlist .
self.myFont is defined as follows:
import tkinter.font as tkFont self.myFont = tkFont.Font(self, "Calibri", 12)
I use the treeview just to show the data and a seperate dictionary to save the data, by using the child-id (returned by insert ) as key. This way I keep the real data I inserted into the treeView. This is important for strings like '0005' which will return as 5 (integer) when you recall it from the treeview and you lose the leading zeros.
I hope this solution helps others. If there is a more convenient solution feel free to comment.
If you have any questions about my code, feel free to ask.
How to change ttk.Treeview column width and weight in Python 3.3?
To display a large set of data in a Tkinter application, we can use the Treeview widget. Generally, we represent data through tables that contain a set of rows and columns. We can add the data in the form of a table with the help of the Treeview widget.
To configure the column width of the Treeview widget, we can use the width and stretch property. It sets the width of the Treeview widget column with the given value.
Example
In this example, we have created a table that contains a list of programming languages. The width of columns ‘ID’ and ‘Programming Language’ is set to their content. Further, we can give a value to set the width of the columns.
# Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win=Tk() # Set the size of the tkinter window win.geometry("700x350") # Create an instance of Style widget style=ttk.Style() style.theme_use('clam') # Add a Treeview widget tree=ttk.Treeview(win, column=("c1", "c2"), show='headings', height=8) tree.column("# 1",anchor=CENTER, stretch=NO, width=100) tree.heading("# 1", text="ID") tree.column("# 2", anchor=CENTER, stretch=NO) tree.heading("# 2", text="Programming Language") # Insert the data in Treeview widget tree.insert('', 'end',text="1",values=('1','C++')) tree.insert('', 'end',text="2",values=('2', 'Java')) tree.insert('', 'end',text="3",values=('3', 'Python')) tree.insert('', 'end',text="4",values=('4', 'Golang')) tree.insert('', 'end',text="5",values=('5', 'JavaScript')) tree.insert('', 'end',text="6",values=('6', 'C# ')) tree.insert('', 'end',text="7",values=('6', 'Rust')) tree.insert('', 'end',text="8",values=('6', 'SQL')) tree.pack() win.mainloop()
Output
Run the above code to display a Table that contains a list of programming languages and Index.
Treeview¶
A treeview widget can display a hierarchy of items. The items are organized in the form of a tree. The parent node is '' and is not displayed. Within a node the items are indexed: 0 being the first item, 'end' representing the position after the last item.
To insert an item to t treeview use the function:
tree.insert(node, index, name, text='Label')
The first example creates a treeview, adds an item at position 0, and another item at position end . The id of the third item is assigned to a local variable in order to use it as a node for creating to sub-items.
from tklib import * app = App('Treeview') tree = ttk.Treeview(App.stack[-1]) tree.grid() tree.insert('', 0, text='Item 1') tree.insert('', 'end', text='Item 2') id = tree.insert('', 5, text='Item 3') tree.insert(id, 0, text='sub-item 0') tree.insert(id, 1, text='sub-item 1') app.run()
Multiple columns¶
The option tree['columns'] adds more columns:
tree['columns'] = ('size', 'modified')
The width, alignment and label of a column can further be specified. To insert values to the new columns use the method set :
tree.set('widgets', 'size', '12KB') tree.set('widgets', 'modified', 'Last week')
To insert all values at creation use the option values :
tree.insert('', 'end', text='Listbox', values=('15KB Yesterday'))
from tklib import * app = App('Treeview - multiple columns') tree = ttk.Treeview(App.stack[-1]) tree.grid() tree.insert('', 'end', 'widgets', text='Widgets') tree.insert('', 0, 'apps', text='Applications') tree['columns'] = ('size', 'modified') tree.column('size', width=50, anchor='center') tree.heading('size', text='Size') tree.heading('modified', text='Modified') tree.set('widgets', 'size', '12KB') tree.set('widgets', 'modified', 'Last week') tree.insert('', 'end', text='Canvas', values=('25KB Today')) tree.insert('apps', 'end', text='Browser', values=('115KB Yesterday')) app.run()
Configure style¶
Like the text and canvas widgets, the Treeview widget uses tags to modify the appearance of lines. Tags are simply a list of strings, such as:
tree.insert('', 'end', text='Item 4', tags=('fg', 'bg'))
Configure the tag with background and foreground color:
tree.tag_configure('bg', background='yellow') tree.tag_configure('fg', foreground='red')
from tklib import * app = App('Treeview - tags') tree = ttk.Treeview(App.stack[-1]) tree.grid() tree.insert('', 'end', text='Item 1', tags=('fg')) tree.insert('', 'end', text='Item 2', tags=('bg')) tree.insert('', 'end', text='Item 2') tree.insert('', 'end', text='Item 4', tags=('fg', 'bg')) tree.tag_configure('bg', background='yellow') tree.tag_configure('fg', foreground='red') app.run()
Bind to events¶
Tags are also used to bind lines to events. This adds a callback to the button click:
This adds 3 virtual events:
tree.tag_bind('cb', '>', cb) tree.tag_bind('cb', '>', cb) tree.tag_bind('cb', '>', cb)
In the callback function cb we print the event, the selection and the focus:
def cb(event): print(event, tree.selection(), tree.focus())
Something like this will be printed to the console:
ButtonPress event num=1 x=8 y=46> ('I002',) I002 VirtualEvent event x=0 y=0> ('I002',) I002 VirtualEvent event x=0 y=0> ('I002',) I002
from tklib import * app = App('Treeview - bind') def cb(event): print(event, tree.selection(), tree.focus()) tree = ttk.Treeview(App.stack[-1]) tree.grid() tree.insert('', 'end', text='Item 1', tags=('cb')) id = tree.insert('', 'end', text='Item 2', tags=('cb')) tree.insert(id, 'end', text='Sub-Item 1', tags=('cb')) tree.insert(id, 'end', text='Sub-Item 2', tags=('cb')) tree.tag_bind('cb', '', cb) tree.tag_bind('cb', '>', cb) tree.tag_bind('cb', '>', cb) tree.tag_bind('cb', '>', cb) app.run()
Two treeviews next to each other¶
from tklib import * app = App('Treeview') items = dir(tk) tree = Treeview() tree['columns'] = ('type', 'value') tree.column('type', width=100) tree.heading('type', text='Type') tree.heading('value', text='Value') for item in items: x = eval('tk.'+item) t = type(x) print(t.__name__, x) tree.insert('', 'end', text=item, values=(t.__name__, x)) items = dir() Treeview(items).grid(row=0, column=1) app.run()
Display a 2D table¶
"""Display a 2D table.""" from tklib import * import random n, m = 40, 10 table = [] for i in range(n): line = [] for j in range(m): line.append(random.randint(0, 999)) table.append(line) class Demo(App): def __init__(self): super().__init__() Label('Display a 2D table', font='Arial 24') Label('Click on header to sort') Combobox('A;B;C') tree = Treeview() for i in range(n): tree.insert('', 'end', text=table[i][0], values=table[i][1:]) tree['columns'] = list(range(m-1)) headings=list('ABCDEFGHI') for j in range(m-1): tree.column(j, width=50, anchor='e') tree.heading(j, text=headings[j]) if __name__ == '__main__': Demo().run()
Insert items into a treeview¶
"""Insert items to the tree.""" from tklib import * class Demo(App): def __init__(self): super().__init__() Label('Insert items to the tree', font='Arial 24') App.text = Entry('Text', 'print(self.val.get())') App.index = Spinbox('Index', 'print(self.val.get())', to=100) Button('Insert', 'App.tree.insert("", App.index.val.get(), text=App.text.get())') Button('Insert to Folder', 'App.tree.insert("folder", App.index.val.get(), text=App.text.get())') App.tree = Treeview() L = 'Hello;Dolly;How;Are;You'.split(';') for item in L: App.tree.insert('', 'end', text=item) App.tree.insert('', 0, 'folder', text='Folder') if __name__ == '__main__': Demo().run()
Add items to specific column¶
"""Insert multiple columns to the tree.""" from tklib import * class Demo(App): def __init__(self): super().__init__() Label('Columns', font='Arial 24') App.tree = Treeview() # App.tree['columns'] = ('size', 'date', 'type') App.tree['columns'] = range(3) App.text = Entry('Text', 'print(self.val.get())') App.row = Spinbox('Row:', 'print(self.val.get())', to=100) App.col = Spinbox('Column:', 'print(self.val.get())', to=100) Button('Set', 'App.tree.set(App.tree.focus(), App.col.val.get(), App.text.get())') for i in range(2): App.tree.column(i, width=100, anchor='w') App.tree.heading(i, text='Heading' + str(i)) L = 'Hello;Dolly;How;Are;You'.split(';') for item in L: App.tree.insert('', 'end', text=item) if __name__ == '__main__': Demo().run()
Customize the treeview widget¶
"""Custumize the Treeview widget.""" from tklib import * class Demo(App): def __init__(self): super().__init__() Label('Customizing the Treeview widget', font='Arial 24') App.tree = Treeview() App.tree['columns'] = range(3) Spinbox('height=', 'App.tree["height"]=self.var.get()', to=20) Spinbox('width=', 'App.tree.column("#0", width=self.var.get())', inc=50, to=500) Spinbox('width 0=:', 'App.tree.column(0, width=self.var.get())', inc=50, to=500) Spinbox('width 1=:', 'App.tree.column(1, width=self.var.get())', inc=50, to=500) Combobox('selectmode=', 'browse;extended;none', 'App.tree["selectmode"]=self.var.get()') Button('show tree', "App.tree['show']='tree'") Button('show headings', "App.tree['show']='headings'") Checkbutton('tree;headings') for i in range(2): App.tree.column(i, width=100, anchor='w') App.tree.heading(i, text='Heading' + str(i)) L = 'Hello;Dolly;How;Are;You'.split(';') for item in L: App.tree.insert('', 'end', text=item) if __name__ == '__main__': Demo().run()
© Copyright 2019-2020, Raphael Holzer Revision e7a7697a .
Versions latest Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.