K
The problem is, selection_get is not a method of its own ListBox, it is common to all widgets that export to the X system or to clipboard on Windows the selected. You have no way of knowing that widgets exported that text, in fact it might not be one of yours. ListBox if you interact with other widgets that also export your selection.You can get the item from a ListBox with listbox.get(indice). To get the index you can't use tk.ACTIVE because even if you click on another list the first will still have an active one. What you can use is listbox.curselection. This gives us another problem, if all the lists lose focus there will be nothing selected.I tend to focus this by creating a custom class that allows grouping several listbox so that only one item can be selected from all, in addition to facilitating the obtaining of the item in itself:import tkinter as tk
class Group:
def init(self):
self._widgets = []
def add_widget(self, widget_instance):
if widget_instance not in self._widgets:
self._widgets.append(widget_instance)
def remove_widget(self, widget_instance):
try:
self._widgets.remove(widget_instance)
except ValueError:
pass
def __contain__(self, obj):
return obj in self._widgets
def __iter__(self):
self._index = 0
return self
def __next__(self):
try:
widget = self._widgets[self._index]
except IndexError:
raise StopIteration()
self._index += 1
return widget
class GroupListbox(tk.Listbox):
def __init__(self, parent, *args, group=None, **kwargs):
super().__init__(parent, *args, **kwargs)
self.root = parent
self.configure(exportselection=False)
self.bind("<<ListboxSelect>>", self._on_select)
self._group = None
self.group = group or Group()
self.selected_row = None
def _on_select(self, _):
if csel:= self.curselection():
self.selected_row = self.get(csel)
if self.group is not None:
for child in self.group:
if child is not self:
child.selection_clear(0, tk.END)
child.selected_row = None
@property
def group(self):
return self._group
@group.setter
def group(self, group):
if group is None:
if self._group is not None:
self._group.remove_widget(self)
self.group = Group()
elif not isinstance(group, Group):
raise ValueError(
f"{self.__name__}.group debe ser una instancia de Group o None"
)
else:
self._group = group
self.group.add_widget(self)
class Test(tk.Frame):
def init(self, parent, *args, **kwargs):
super().init(parent, *args, **kwargs)
frame = self
lb_group = Group()
self.listbox1 = GroupListbox(frame, width=35, height=28, group=lb_group)
activos = ['Caja', 'Banco', 'Valores a depositar','Moneda extranjera',
"Fondo fijo", "Titulos y acciones", "Deudores varios",
"Deudores por venta","Deudores morosos","Deudores en litigio",
"Documentos a cobrar", "Concepto pagado poadelantado",
"Hipotecas a cobrar","Anticipios proveedores", "Accionistas",
"Mercaderias", "Materias primas",
"Productos en proceso de elaboracion","Productos terminados",
"Rodados", "Instalaciones", "Muebles y utiles", "Inmuebles",
"Maquinarias", "Llave de negocio", "Marcas y patentes",
"Derechos de autor", "Gastos de organizacion"]
self.listbox1.insert(0, *activos)
self.listbox1.grid(row=3, column=0)
self.listbox2 = GroupListbox(frame, width=35, height=28, group=lb_group)
pasivos = ["Proveedores", "Acreedores varios", "Documentos a pagar",
"Intereses a pagar", "Obligaciones negociables",
"Prestamos a pagar", "Acreedores prendarios e hipotecarios",
"Adelantos en cuenta corriente", "Honorarios a pagar",
"Sueldos a pagar", "Anses a pagar",
"Retencion impuesto a las ganancias", "Retencion IVA",
"Dividendos", "Concepto cobrado por adelantado",
"Anticipo de clientes", "Cuentas por pagar", "Previsiones"]
self.listbox2.insert(0, *pasivos)
self.listbox2.grid(row=3, column=1)
self.listbox3 = GroupListbox(frame, width=35, height=28, group=lb_group)
resultados = ['Gastos Luz','Descuento obtenido','Descuento otorgado',
'Interes otorgado','Interes obtenido', 'Ventas','CMV',
'Alquileres cobrados', 'Comision Cobrada', 'Impuestos',
'Alquileres pagados', 'Sueldos y jornales',
'Gastos generales', 'Comisiones pagadas',
'Publicidad', 'Seguros']
self.listbox3.insert(0, *resultados)
self.listbox3.grid(row=3, column=2)
self.listbox1.selection_clear(0, tk.END)
self.listbox2.selection_clear(0, tk.END)
self.listbox3.selection_clear(0, tk.END)
tk.Button(frame, text="aceptar", command=self.add_product).grid(row=4, column=1)
def add_product(self):
if rows:= (self.listbox1.selected_row or self.listbox2.selected_row):
print(f"Ejecutado el if, row: '{rows}'")
elif rows:= self.listbox3.selected_row:
print(f"Ejecutado el elif, row: '{rows}'")
else:
print("Ejecutado el else, nada seleccionado")
if name == "main":
root = tk.Tk()
Test(root).pack()
root.mainloop()