Seth M
Seth M

Reputation: 13

How can I update a tkinter Label with every new selection in Listbox?

I would like the labels on the right side to update when a name in the list box is selected. When a new name in the list is selected, the name label on the right remains the same.

I tried name_list.index(ACTIVE) directly within student_name.set() as student_name.set(students_list[name_list.index(ACTIVE)].get_name()). I'm afraid that it is just using index 0 and not even using active selection.

from tkinter import *

# Defining Student class
class Student:

  def __init__(self, name, instrument=""):
    self.name = name
    self.instrument = instrument

  def get_name(self):
    return self.name

  def get_instrument(self):
    return self.instrument

# Creating Student objects and list
s1 = Student("Seth", "Trumpet")
s2 = Student("Cassie", "Flute")
s3 = Student("Cody", "Guitar")
students_list = [s1, s2, s3]

# GUI created
def make_window():
  rootWindow = Tk()
  rootWindow.title("Instructor Database Application")
  rootWindow.grid()

  frame0 = Frame(rootWindow)
  frame0.grid(column=0, row=0, padx=20, pady=20)

  name_list = Listbox(frame0, height=10)
  name_list.grid(column=0, row=0)
  for Student in students_list:
    name_list.insert(END, Student.get_name())

  frame1 = Frame(rootWindow)
  frame1.grid(column=1, row=0, padx=20, pady=20)

  student_index = name_list.index(ACTIVE)
  student_name = StringVar()
  student_name.set(students_list[student_index].get_name())

  name_label = Label(frame1, textvariable=student_name)
  name_label.grid(column=0, row=0)

  instrument_label = Label(frame1, text="Instrument")
  instrument_label.grid(column=0, row=1)

  return rootWindow

def main():
  app = make_window()
  app.mainloop()

main()

The program begins with the first name and is unable to change. Any advice?

Upvotes: 0

Views: 1773

Answers (1)

furas
furas

Reputation: 142641

You have to bind function to listbox which will be executed when you change selection. And this function has to change text in label

listbox.bind('<<ListboxSelect>>', my_function)

Minimal working example

import tkinter as tk

# --- function ---

def on_selection(event):
    # here you can get selected element
    print('previous:', listbox.get('active'))
    print(' current:', listbox.get(listbox.curselection()))

    # or using `event`

    #print('event:', event)
    #print('widget:', event.widget)
    print('(event) previous:', event.widget.get('active'))
    print('(event)  current:', event.widget.get(event.widget.curselection()))

    lbl['text'] = "Seleced: " + listbox.get(listbox.curselection())
    print('---')

# --- main ---

root = tk.Tk()

listbox = tk.Listbox(root)
listbox.pack()

listbox.insert(1, 'Hello 1')
listbox.insert(2, 'Hello 2')
listbox.insert(3, 'Hello 3')
listbox.insert(4, 'Hello 4')
listbox.bind('<<ListboxSelect>>', on_selection)

lbl = tk.Label(root, text='?')
lbl.pack()

root.mainloop()

Upvotes: 2

Related Questions