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.

1

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.