Tkinter Treeview出现的可用空间

问题描述 投票:0回答:1

按下简单调用fill_table()功能的按钮后,表格中将出现可用空间。为什么会发生这种情况以及如何避免这种情况?我的代码:

import tkinter as tk
import tkinter.ttk as ttk


def fill_table():
    required_columns = ['col1', 'col2', 'col3']
    table_treeview["columns"] = required_columns
    table_treeview["show"] = "headings"
    for col in required_columns:
        table_treeview.column(col, width=90)
        table_treeview.heading(col, text=col)


root = tk.Tk()

table_treeview = ttk.Treeview(root)
table_treeview.pack()

button = tk.Button(root, text='Restart', command=fill_table)
button.pack()

fill_table()


root.mainloop()

图像:

  • 按下按钮之前:

    enter image description here

  • 按下按钮后:

    enter image description here

python tkinter treeview tk ttk
1个回答
0
投票

看来,如果您在启动mainloop之后运行它,那么它不会等到函数结束时重绘窗口小部件,但是当您创建新列时,它将使用默认大小创建它并刷新窗口,从而调整窗口大小。之后,将width=90更改回较小的尺寸,但不会更改窗口的尺寸-因此窗口中有空白。

但是如果我在table_treeview["show"] = "headings"之后使用width=90,则它不会调整列的大小,并且窗口不会更改大小

(在Linux Mint上测试)


我为列使用了第二个函数,并使用了不同的名称,以查看它是否在方便地更改列。

import tkinter as tk
import tkinter.ttk as ttk


def fill_table():
    required_columns = ['col1', 'col2', 'col3']
    table_treeview["columns"] = required_columns
    for col in required_columns:
        table_treeview.column(col, width=90)
        table_treeview.heading(col, text=col)
    table_treeview["show"] = "headings"  # use after setting column's size

def fill_table_2():
    required_columns = ['colA', 'colB', 'colC']
    table_treeview["columns"] = required_columns
    for col in required_columns:
        table_treeview.column(col, width=90)
        table_treeview.heading(col, text=col)
    table_treeview["show"] = "headings"  # use after setting column's size

root = tk.Tk()

table_treeview = ttk.Treeview(root)
table_treeview.pack()

button = tk.Button(root, text='Restart', command=fill_table_2)
button.pack()

fill_table()

root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.