Reputation: 197
Good day,
I have a python application that produces multiple listboxes each with it's own list of data. These listboxes are created dynamically according to the length of a user generated list.
I have a button that when clicked i want to trigger some code to effect the active listbox (removing the value from the list amongst other things).
So my plan is to iterate through all the listboxes and only delve deeper if the list box has focus. But alas, after 2-3 hours of peeling through questions and tkinter documentation I cannot find any way to determine if something has focus or not.
Thanks in advance!
Upvotes: 2
Views: 1919
Reputation: 76194
Widgets are capable of emitting <FocusIn>
and <FocusOut>
events, so you can bind callbacks in order to manually keep track of which listbox has focus. Example:
from Tkinter import *
class App(Tk):
def __init__(self, *args, **kargs):
Tk.__init__(self, *args, **kargs)
self.focused_box = None
for i in range(4):
box = Listbox(self)
box.pack()
box.insert(END, "box item #1")
box.bind("<FocusIn>", self.box_focused)
box.bind("<FocusOut>", self.box_unfocused)
button = Button(text="add item to list", command=self.add_clicked)
button.pack()
#called when a listbox gains focus
def box_focused(self, event):
self.focused_box = event.widget
#called when a listbox loses focus
def box_unfocused(self, event):
self.focused_box = None
#called when the user clicks the "add item to list" button
def add_clicked(self):
if not self.focused_box: return
self.focused_box.insert(END, "another item")
App().mainloop()
Here, clicking the button will add "another item" to whichever listbox has focus.
Upvotes: 3