-1

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

根据我通过谷歌搜索发现的信息,我可以在树视图上使用 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()
4

1 回答 1

0

请注意,在里面clear(),你已经self.tree_view在 line中使用了for item in ...,而self.tree在 for 循环块中使用了:

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()不返回任何东西的结果:

self.tree_view = self.create_tree_view()

其实你不需要self.tree_view,用self.treeclear()

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
于 2022-02-21T15:12:03.467 回答