python tkinter - 删除所有 TreeView 子项

python tkinter - Deleting all TreeView Children

我想创建一个清除按钮,用于删除树视图中的所有记录,同时,我正在尝试通过 Tkinter 改进我的 OOP。 (因此,如果代码中还有其他非最佳实践;请您也提出建议)。

根据我通过谷歌搜索发现的情况,我可以在 treeview 上使用 get_children 方法,检索它们,然后再删除它们。

def delButton(self):
    x = main.tree.get_children()
    for item in x:
        main.tree.delete(item)

但是,我不断收到属性错误:AttributeError:'NoneType' 对象没有属性 'get_children'。这是我在 类 中引用的方式吗?

import tkinter as tk
from tkinter import ttk,messagebox


gray = '#808080'
green = '#7FFF00'
black = '#000000'
filter_font = ('Arial',12,'bold')
search_font = ('Arial',10)

class News:
    def __init__(self):
        self.window = tk.Tk()
        self.window.geometry("1000x500")
        self.window.resizable(0,0)


        self.quit_button = self.create_quit_button()
        self.clear_button = self.create_clear_button()

        self.tree_view = self.create_tree_view()




    def create_tree_view(self):
        self.tree = ttk.Treeview(self.window,columns=(1,2,3,4) , show= 'headings',height='12')
        self.tree.grid(row=0, column=0, rowspan=6, columnspan=9, padx=10, pady=10)

        self.tree.column(1,width=70)
        self.tree.column(2,width=70)

        self.tree.heading(1,text ='Hello',anchor='w')
        self.tree.heading(2,text ='World',anchor='w')

        self.tree.insert(parent='',index='end',iid=0,values = ['John','John@gmail.com'])
        self.tree.insert(parent='',index='end',iid=1,values = ['John','John@gmail.com'])



        self.tree.grid(row=0, column=0, rowspan=6, columnspan=9, padx=10, pady=10)


    def create_clear_button(self):
        self.clear_button = tk.Button(self.window,text='Clear',fg=green,bg = black,command = lambda : self.clear())
        self.clear_button.grid(row=0,column=20)

    def create_quit_button(self):
        quit_button = tk.Button(self.window,text='Quit',fg=green,bg = black,command =lambda: self.quit())
        quit_button.grid(row =4,column = 10)


    def quit(self):
        self.window.quit()

    def run(self):
        self.window.mainloop()


    def clear(self):
        for item in self.tree_view.get_children():
            self.tree.delete(item)
        return (self.tree)

if __name__ == '__main__':
    news = News()
    news.run()

请注意,在 clear() 中,您在行 for item in ... 中使用了 self.tree_view,而在 for 循环块中使用了 self.tree

def clear(self):
    for item in self.tree_view.get_children(): # used self.tree_view
        self.tree.delete(item)                 # used self.tree
    return (self.tree)

self.tree_viewNone 因为它是 create_tree_view() 的结果,它没有 return 任何东西:

self.tree_view = self.create_tree_view()

其实你不需要self.tree_view,在clear()中使用self.tree:

def clear(self):
    for item in self.tree.get_children(): # used self.tree instead
        self.tree.delete(item)
    #return (self.tree) # return here is useless as clear() is triggered by a button