0

I've code like below:

from tkinter import *

root = Tk()
root.title("sample program")

def print_item_from_list(event):
    print(variable)

list = [1, 2, 3, 4, 5]
seclist = []
print(list)
for i in range(0,5):
    variable = list[i]
    sample = Label(text=variable)
    sample.pack()
    sample.bind('<Enter>', print_item_from_list)

root.mainloop()

What I want to achieve is that everytime my pointer enter label 'Sample', specified item form list is printed (i.e. when I hover over label '2', I want second object from my list to get printed). I tried already changing variable to list[i] (Just for tests if it would work) and creating second list and appending to it, but with no luck. My guess is it's somehow connected to Tkniter behaviour.

PotatoBox
  • 583
  • 2
  • 10
  • 33

2 Answers2

2

With your code :

from tkinter import *

root = Tk()
root.title("sample program")

def print_item_from_list(event):
    print(event.widget.config("text")[-1])


list = [1, 2, 3, 4, 5]
seclist = []
print(list)
for i in range(0,5):
    variable = list[i]
    sample = Label(text=variable)
    sample.pack()
    sample.bind('<Enter>', print_item_from_list)

root.mainloop()
dsgdfg
  • 1,492
  • 11
  • 18
1

You can make use of closures:

for i in range(0,5):
    variable = list[i]
    sample = Label(text=variable)
    sample.pack()
    def connect_callback(variable):
        sample.bind('<Enter>', lambda event:print(variable))
    connect_callback(variable)

This creates a new callback function with a fixed value for each label. In your code, all callbacks refer to the same variable, but with this solution every callback has its own variable.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149