Tkinter Selection_clear() 不工作

Tkinter Selection_clear() not working

我正在尝试制作一个简单的搜索列表框,其中包含很多变量,因此有必要使用 'clear selected' 函数。为此,我创建了一个 'Clear' 按钮并尝试使用 tk 的 selection_clear 函数 link 它。不幸的是我无法让它工作。你能给我指明正确的方向吗?

代码摘录:

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
        self.create_widgets()

    def create_widgets(self):
        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=0)

        parameters_list_1 = 'foo', 'bar', 'foofoo', 'barbar', 'foobar'
        self.sb1_values = tk.Variable(value=parameters_list_1)
        self.search_listbox = tk.Listbox(self, activestyle='dotbox', listvariable=self.sb1_values, selectmode=tk.MULTIPLE)
        self.search_listbox.grid(row=3, column=1, sticky=tk.N+tk.S+tk.E+tk.W)

        self.clear_button = tk.Button(self, text='Clear', command=self.search_listbox.selection_clear(0, tk.END))
        self.clear_button.grid(row=4, column=2, sticky=tk.N+tk.S+tk.E+tk.W)

app = Application()
app.master.title('GUI')
app.mainloop()

提前致谢

创建一个单独的函数来清除它 -

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
        self.create_widgets()

    def create_widgets(self):
        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=0)

        parameters_list_1 = 'foo', 'bar', 'foofoo', 'barbar', 'foobar'
        self.sb1_values = tk.Variable(value=parameters_list_1)
        self.search_listbox = tk.Listbox(self, activestyle='dotbox', listvariable=self.sb1_values, selectmode=tk.MULTIPLE)
        self.search_listbox.grid(row=3, column=1, sticky=tk.N+tk.S+tk.E+tk.W)

        self.clear_button = tk.Button(self, text='Clear', command=self.clear_search)
        self.clear_button.grid(row=4, column=2, sticky=tk.N+tk.S+tk.E+tk.W)

    def clear_search(self):
        print(tk.END)
        self.search_listbox.selection_clear(0, tk.END)



app = Application()
app.master.title('GUI')
app.mainloop()

command=self.search_listbox.selection_clear(0, tk.END)替换为command=lambda : self.search_listbox.selection_clear(0, tk.END)