Home > Net >  How to read clickable labels in tkinter
How to read clickable labels in tkinter

Time:12-10

I asked this question yesterday in a way to long manner. I now reduced the code to the real problem. When I click the link in the window I want the read the pos_num. This way I can get information from other lists which are in the complete code.

If I can get the following to work I can implement it in my tool.

import tkinter as tk


def track_and_trace(pos_num):
    print(pos_num)


# Create list
test_list = ["link1", "link2", "link3", "link4"]

# Create a UI window
window = tk.Tk()

# Check how many rows the window will get
number_of_rows = len(test_list)

# Add values from list to the tkinter window
row_number = 1
while row_number <= number_of_rows:
    label_link = tk.Label(window, text=test_list[row_number - 1], width=13, cursor="hand2")
    label_link.grid(row=row_number, column=1, sticky='ew')
    label_link.bind("<Button-1>", lambda pos_num=test_list[row_number - 1]: track_and_trace(pos_num))

    row_number  = 1

# Start the window loop
window.mainloop()

CodePudding user response:

You can access the text property by using the event like this:

import tkinter as tk


def track_and_trace(e:tk.Event):
    print(e.widget["text"])


# Create list
test_list = ["link1", "link2", "link3", "link4"]

# Create a UI window
window = tk.Tk()

# Check how many rows the window will get
number_of_rows = len(test_list)

# Add values from list to the tkinter window
row_number = 1
while row_number <= number_of_rows:
    label_link = tk.Label(window, text=test_list[row_number - 1], width=13, cursor="hand2")
    label_link.grid(row=row_number, column=1, sticky='ew')

    label_link.bind("<Button-1>", lambda e: track_and_trace(e))

    row_number  = 1

# Start the window loop
window.mainloop()

ps: i recommend using for instead of while

  • Related