Tkinter shortcut bound to StringVar is one click on update

The problem I am facing is that when I click on the different file names in the Listbox , the Label value changes the value by one click behind what I am currently clicking.

What am I missing here?

 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() 
+4
source share
1 answer

The problem is with the fundamental design of Tk. In the short version, bindings to specific widgets light up before the default class bindings for the widget. In class bindings, the list selection changes. This is exactly what you are observing - you see the selection before the current click.

The best solution is to bind to the virtual event <<ListboxSelect>> , which is fired after changing the selection. Other solutions (unique to Tk and what gives it incredible power and flexibility) are to change the binding order. This includes either moving the bindtag widget after the bindtag class, or adding a new bindtag after binding the class and binding it to it.

Since binding to <<ListboxSelect>> is the best solution, I will not go into details on how to change the binding, although this is straightforward, and I think it is well documented.

+4
source

Source: https://habr.com/ru/post/923213/


All Articles