MC2020
MC2020

Reputation: 47

Referencing an adjacent Label Text

I am trying to write a function to print the text on the label corresponding to the adjacent button. I am having trouble with this. I would like to print "a" if I click the first button, "b" if I click the second button, and "c" if I click the third button. How do I design the code so that the buttons will know which label it should print?

import tkinter as tk
from tkinter import *
from tkinter import ttk

dummylist = ["a","b","c"]

root = tk.Tk()

def print_dummylistvar():
    print(lbl)


for x in range(len(dummylist)):
    lbl = Label(root, text=dummylist[x])
    lbl.grid(column=0, row=x)
    button = tk.Button(root, text='Print', command=print_dummylistvar)
    button.grid(column=1, row=x)

root.mainloop()

Upvotes: 0

Views: 38

Answers (1)

furas
furas

Reputation: 143187

You can use lambda to assign function with argument to command=

command=lambda:print_dummylistvar(lbl)

But because you create many labels in loop so you will need also arg=lbl to copy reference from lbl to new variable.

command=lambda arg=lbl:print_dummylistvar(arg)

Without this all buttons will use reference to the same label - last label created in for-loop

It will need to print lbl['text']

def print_dummylistvar(widget):
    print(widget['text'])

Working code

import tkinter as tk
#from tkinter import * # PEP8: `import *` is not preferred
from tkinter import ttk

# --- functions ---

def print_dummylistvar(widget):
    print(widget['text'])

# --- main ---

dummylist = ["a", "b", "c"]

root = tk.Tk()

for number, text in enumerate(dummylist):
    lbl = tk.Label(root, text=text)
    lbl.grid(column=0, row=number)
    button = tk.Button(root, text='Print', command=(lambda arg=lbl:print_dummylistvar(arg)))
    button.grid(column=1, row=number)

root.mainloop()

BTW: Instead reference to label you can also use directly text

button = tk.Button(root, text='Print', command=(lambda arg=text:print_dummylistvar(arg)))

and it gets text instead label so it doesn't need lbl['text']

def print_dummylistvar(text):
    print(text)

import tkinter as tk
from tkinter import ttk

# --- functions ---

def print_dummylistvar(text):
    print(text)

# --- main ---

dummylist = ["a", "b", "c"]

root = tk.Tk()

for number, text in enumerate(dummylist):
    lbl = tk.Label(root, text=text)
    lbl.grid(column=0, row=number)
    button = tk.Button(root, text='Print', command=(lambda arg=text:print_dummylistvar(arg)))
    button.grid(column=1, row=number)

root.mainloop()

Upvotes: 1

Related Questions