pythonpython-3.xtkinterlistboxlistboxitem

Why am I not getting the selected value from the tkinter listbox?


`from tkinter import *
pencere = Tk()
başlık = pencere.title("deneme2")
etiket = Label(text="")
etiket.pack()

def göster(event):
    etiket["text"] = "%s seçildi."%liste.get(ACTIVE)
    etiket.pack()
liste = Listbox()
liste.insert(1, "İstanbul")
liste.insert(2, "Ankara")
liste.insert(3, "İzmir")
liste.insert(4, "İzmit")
liste.insert(5, "Antalya")
liste.insert(6, "Bursa")
liste.pack()

liste.bind("<Button-1>",göster)
mainloop()`

here is the problem! I follow an online course and couldn't figure out why it would show the wrong text. I choose İzmir it says İstanbul, I choose Ankara it says İstanbul, I choose İstanbul it says Ankara, other ones are like this too.


Solution

  • Your code is working. Just double click it. You don't need etiket.pack() inside the göster function. I had to rearrange our code to make it more readable. Just double click it. I also added widget for Label and Listbox.

    from tkinter import *
    
    
    pencere = Tk()
    başlık = pencere.title("deneme2")
     
    
    def göster(event):
        etiket.config(text = "%s seçildi."%liste.get(ACTIVE))
    
    etiket = Label(pencere)
    etiket.pack()
    
    liste = Listbox(pencere)
    liste.insert(0, "İstanbul")
    liste.insert(1, "Ankara")
    liste.insert(2, "İzmir")
    liste.insert(3, "İzmit")
    liste.insert(4, "Antalya")
    liste.insert(5, "Bursa")
     
    liste.pack()
    etiket.pack()
    
    liste.bind("<Button-1>",göster)
     
    mainloop()