Python - Tkinter 按钮命令不工作

Python - Tkinter Button Command not Working

class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.search_var = StringVar()
        self.search_var.trace("w", lambda name, index, mode: self.update_list())
        self.entry = Entry(self, textvariable=self.search_var, width=13)
        self.lbox = Listbox(self, width=50, height=30, selectmode=EXTENDED)
        self.rbox = Listbox(self, width=50, height=30)
        self.btnGet = Button(self, text="Add to Selection", command=self.get_selection())

        self.entry.grid(row=0, column=0, padx=10, pady=3)
        self.lbox.grid(row=1, column=0, padx=10, pady=3)
        self.rbox.grid(row=1, column=1, padx=10, pady=3)
        self.btnGet.grid(row=2, column=0, padx=10, pady=3)

        self.update_list()

    def get_selection(self):
        print("Get Selection")
        items = [self.lbox_list[int(item)] for item in self.lbox.curselection()]
        print(items)


def main():
    root = Tk()
    root.title('Filter Listbox Test')
    app = Application(master=root)
    print('Starting mainloop()')
    root.mainloop()


main()

我的代码从 XML 文件读取并填充列表框。我想要一个按钮将我的选择从 lbox 复制到 rbox。但是我的按钮似乎没有触发,我不确定为什么。

在 tkinter 中指定命令时,您应该使用:

command=self.get_selection

而不是:

command=self.get_selection()

类似于为你的线程定义一个函数!否则它不会将您的函数与命令正确关联