更新时绑定到StringVar的Tkinter标签落后一键


问题内容

我在这里遇到的问题是,当我单击中的不同文件名时ListboxLabel更改的值将在我当前单击的内容后面单击。

我在这里想念什么?

import Tkinter as tk

class TkTest:

    def __init__(self, master):

        self.fraMain = tk.Frame(master)
        self.fraMain.pack()

        # Set up a list box containing all the paths to choose from
        self.lstPaths = tk.Listbox(self.fraMain)
        paths = [
            '/path/file1',
            '/path/file2',
            '/path/file3',
        ]
        for path in paths:
            self.lstPaths.insert(tk.END, path)
        self.lstPaths.bind('<Button-1>', self.update_label)
        self.lstPaths.pack()

        self.currentpath = tk.StringVar()
        self.lblCurrentPath = tk.Label(self.fraMain, textvariable=self.currentpath)
        self.lblCurrentPath.pack()

    def update_label(self, event):
        print self.lstPaths.get(tk.ACTIVE),
        print self.lstPaths.curselection()
        self.currentpath.set(self.lstPaths.get(tk.ACTIVE))

root = tk.Tk()
app = TkTest(root)
root.mainloop()

问题答案:

问题与Tk的基本设计有关。简短的版本是,特定窗口小部件的绑定在窗口小部件的默认类绑定之前触发。在类绑定中,列表框的选择被更改。这正是您所观察到的-
您在当前点击之前就看到了选择。

最好的解决方案是绑定到<<ListboxSelect>>选择更改后触发的虚拟事件。其他解决方案(对于Tk来说是独一无二的,并为其赋予了其令人难以置信的强大功能和灵活性)是修改绑定的应用顺序。这涉及将窗口小部件绑定标签移动到类绑定标签之后,或者在类绑定标签之后添加新的绑定标签并将其绑定到该绑定标签。

由于绑定到<<ListboxSelect>>是更好的解决方案,因此我将不介绍如何修改绑定标签的详细信息,尽管它很简单,而且我认为它已被很好地记录在案。