How to get a Treeview columns to fit the Frame it is within

北城余情 提交于 2021-01-29 02:03:52

问题


When dynamically changing a treeviews data, I want the rows to expand to the size of the treeview's frame. Currently if I make the GUI fullscreen and re-fill the data it only uses a small portion of the available screen-size, i.e. the columns don't resize or stretch to fill the width of the screen (i'm not too concerned with the rows filling). I have produced a minimal working example below:


import tkinter as tk
from tkinter import ttk
import random 

class App():

    def __init__(self):

        self.root = tk.Tk()

        self.frame = tk.Frame(self.root)
        self.frame.pack(expand=True, fill=tk.BOTH)

        self.tree = ttk.Treeview(self.frame, show="headings")
        self.tree.pack(expand=True, fill=tk.BOTH)

        self.button = ttk.Button(self.root, text="Fill", command=self.fill)
        self.button.pack(side=tk.BOTTOM,expand=True,fill=tk.X)

        self.root.mainloop()

    def fill(self):

        if self.has_data():
            self.tree.delete(*self.tree.get_children())

        i = random.randrange(1,10)
        self.tree["columns"]=tuple([str(i) for i in range(i)])

        for col in self.tree['columns']:
            self.tree.heading(col, text="Column {}".format(col), anchor=tk.CENTER)
            self.tree.column(col, anchor=tk.CENTER)

        j = random.randrange(10)

        for j in range(j):

            self.tree.insert("", "end", values = tuple([k for k in range(i)]))

    def has_data(self):

        has_tree = self.tree.get_children()

        return True if has_tree else False


App()

Note that resizing the GUI myself resizes the columns automatically.


回答1:


The issue is that the columns are created with an initial size (default is 200 pixels I think) and only stretch if the treeview is resized after their creation. So you will have to manually set the column width to occupy the whole available space. To do so you can use the width argument of the column() method of the treeview:

self.tree.column(col, width=col_width)

where col_width is the total width divided by the number of columns. Incorporating this code in the fill() function gives

def fill(self):

    if self.has_data():
        self.tree.delete(*self.tree.get_children())

    i = random.randrange(1,10)
    self.tree["columns"]=tuple([str(i) for i in range(i)])

    col_width = self.tree.winfo_width() // i # compute the width of one column

    for col in self.tree['columns']:
        self.tree.heading(col, text="Column {}".format(col), anchor=tk.CENTER)
        self.tree.column(col, anchor=tk.CENTER, width=col_width)  # set column width

    j = random.randrange(10)

    for j in range(j):

        self.tree.insert("", "end", values = tuple([k for k in range(i)]))


来源:https://stackoverflow.com/questions/57772458/how-to-get-a-treeview-columns-to-fit-the-frame-it-is-within

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!