Home > database >  How to create new toplevel window with treeview object?
How to create new toplevel window with treeview object?

Time:10-19

i cant figure out why this code is not working. I am trying to make a treeview in new Toplevel window after clicking on a Button. But when i add a scrollbar to treeview - treeview disappear (I comment the part wih scrollbar). Here is code:

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()

CodePudding user response:

You are redefining self to be the ttk.Treeview instance. Later, when you create the scrollbar, this cause the scrollbar to be a child of the ttk.Treeview widget.

You should definitely not be redefining self. Use a different variable, such as tree. Or better, use self.tree so that you can reference the tree from other methods.

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')
  • Related