richrow
richrow

Reputation: 117

How to 'fix' selected item in tkinter.Listbox?

Here's is an extract from my code:

import tkinter as tk

def evaluate(event):
    print(list_box.curselection())
    
root = tk.Tk()
var = tk.StringVar()
var.set(0)

entry = tk.Entry(root, textvariable = var)
entry.place(x = 150, y = 0, width = 20)
entry.bind("<Return>", evaluate)


list_box = tk.Listbox(root, selectmode = 'single')
list_box.place(x = 0, y = 0)
lst = [1, 2, 3]

for elem in lst:
    list_box.insert('end', elem)

list_box.selection_set(first = 0)
list_box.bind("<<ListboxSelect>>", evaluate)

root.mainloop()

The problem is that I want to 'fix' somehow the last selected value in the tkinter.Listbox. I mean, if in the window we type something to the entry, then in some cases (probably, it depends on how you click the entry box) the value chosen in the list will be lost. Is it possible to save, for example, the last selected value?

I'm new to Python and, in particular, to tkinter package, so any help would be appreciated.

Upvotes: 0

Views: 408

Answers (1)

Thingamabobs
Thingamabobs

Reputation: 8037

the problem is as soon as you select something else like the input of the entry, your listbox lose the shown selection. I removed the default binding for double click, but if you still want to use it to write input, I can't remove the single click (B1-Motion dosent works either). At least I dont know how. I recommand to use the entry just as display or vise versa.

import tkinter as tk

def evaluate(event):
  print(list_box.curselection())


root = tk.Tk()
var = tk.StringVar()
var.set(0)

entry = tk.Entry(root, textvariable = var)
entry.place(x = 150, y = 0, width = 20)
entry.bind("<Return>", evaluate)
entry.bind('<Double-Button-1>', lambda e: "break")


list_box = tk.Listbox(root, selectmode = 'single')
list_box.place(x = 0, y = 0)
lst = [1, 2, 3]

for elem in lst:
    list_box.insert('end', elem)

list_box.selection_set(first = 0)
list_box.bind("<<ListboxSelect>>", evaluate)

root.mainloop()

Upvotes: 1

Related Questions