设置Treeview的行高会使其他小部件在网格中不可见.为什么会发生这种情况



我试图通过使用ttk来提高树视图中的行高度。样式配置方法。但是,这使得其他按钮不可见,为什么会发生这种情况?我该怎么解决这个问题?

import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('My Awesome App')
self.geometry('300x300')
self.b1 = tk.Button(self, text='b1')
self.tree = ttk.Treeview(self)
self.b2 = tk.Button(self, text='b2')
style = ttk.Style(self)
style.configure('Treeview', rowheight=120)  # this line makes app.b1, app.b2 invisible
self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.rowconfigure(2, weight=1)
self.columnconfigure(0, weight=1)
self.b1.grid(row=0, column=0)
self.tree.grid(row=1, column=0)
self.b2.grid(row=2, column=0)

if __name__ == "__main__":
app = App()
app.mainloop()

根据我的经验,位置选项比网格更灵活。下面是一个解决问题的例子。

  1. 将工作区划分为多个框架,并将小部件放入多个框架中。

  2. 将小部件封装在框架内

    import tkinter as tk
    from tkinter import ttk
    
    class App(tk.Tk):
    def __init__(self):
    super().__init__()
    self.title('My Awesome App')
    self.geometry('300x300')
    frame1 = tk.Frame(self, height = 50)
    frame2 = tk.Frame(self, height = 200)
    frame3 = tk.Frame(self, height = 50)
    frame1.place(relwidth = 1, relheight = 0.1, relx = 0, rely = 0)
    frame2.place(relwidth = 1, relheight = 0.8, relx = 0, rely = 0.1)
    frame3.place(relwidth = 1, relheight = 0.1, relx = 0, rely = 0.9)
    self.b1 = tk.Button(frame1, text='b1')
    self.tree = ttk.Treeview(frame2)
    self.b2 = tk.Button(frame3, text='b2')
    style = ttk.Style(self)
    style.configure('Treeview', rowheight=120)  # this line makes app.b1, app.b2 invisible
    self.b1.pack()
    self.tree.pack()
    self.b2.pack()
    
    if __name__ == "__main__":
    app = App()
    app.mainloop()
    

当tk.Treeview的大小超过主框架时,它似乎不能很好地与几何管理器配合使用。因此,我最终制定了一个方法,根据master的大小重新计算列宽和树高,并调整Treeview的大小。此外,它需要首先打包滚动条,以防止滚动条被隐藏。

示例:

class Treeview(ttk.Treeview):
def __init__(self, container, columns, *args, **kwargs):
super(Treeview, self).__init__(container, columns=columns, *args, **kwargs)
self.columns = columns
for column in self.columns:
self.heading(column, text=column, anchor=tk.W)
self.column(column, anchor=tk.CENTER)
def update_man(self):  # call this method when treeview get update
super(Treeview, self).update()
mw, mh = self.master.winfo_width(), self.master.winfo_height()
style = ttk.Style(self)
row_height = style.lookup(self['style'], 'rowheight')
ac = 1 if 'tree' in list([str(x) for x in self['show']]) else 0
col_width = int(mw / (len(self.columns) + ac)) + 1
for cn in range(len(self.columns)+1):
self.column(f'#{cn}', width=col_width)
if type(row_height) == 'int':
row_view_height = int(mh / row_height)
if row_view_height < self['height']:
self['height'] = row_view_height

相关内容

  • 没有找到相关文章

最新更新