如何使用 treeview 对象创建新的顶层 window?

How to create new toplevel window with treeview object?

我不明白为什么这段代码不起作用。单击按钮后,我试图在新的 Toplevel window 中创建树视图。但是当我向 treeview 添加滚动条时 - treeview 消失(我评论了带有滚动条的部分)。这是代码:

from tkinter import*
class Treeview(Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title('Contacts List')
        self.geometry('1050x527')
        columns = ('#1', '#2', '#3', '#4', '#5')
        self = ttk.Treeview(self, columns=columns, show='headings')
        self.heading('#1', text='Name')
        self.heading('#2', text='Birthday')
        self.heading('#3', text='Email')
        self.heading('#4', text='Number')
        self.heading('#5', text='Notes')
        self.grid(row=0, column=0, sticky='nsew')
        #scrollbar = ttk.Scrollbar(self, orient=VERTICAL, command=self.yview)
        #self.configure(yscroll=scrollbar.set)
        #scrollbar.grid(row=0, column=1, sticky='ns')
    root = Tk()
    def tree():
        new= Treeview(root)
    button7 = ttk.Button(root,text="Contacts", command=tree)
    button7.grid(row=1,column=0)
    root.mainloop()

您正在将 self 重新定义为 ttk.Treeview 实例。稍后,当您创建滚动条时,这会导致滚动条成为 ttk.Treeview 小部件的子项。

你绝对不应该重新定义 self。使用不同的变量,例如 tree。或者更好的是,使用 self.tree 以便您可以从其他方法引用树。

class Treeview(Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title('Contacts List')
        self.geometry('1050x527')
        columns = ('#1', '#2', '#3', '#4', '#5')
        self.tree = ttk.Treeview(self, columns=columns, show='headings')
        self.tree.heading('#1', text='Name')
        self.tree.heading('#2', text='Birthday')
        self.tree.heading('#3', text='Email')
        self.tree.heading('#4', text='Number')
        self.tree.heading('#5', text='Notes')
        self.tree.grid(row=0, column=0, sticky='nsew')
        scrollbar = ttk.Scrollbar(self, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=scrollbar.set)
        scrollbar.grid(row=0, column=1, sticky='ns')