Mruusi
Mruusi

Reputation: 43

How to let a tkinter button return it's text value

So I have this code and want the button to return it's text value when being clicked.

film = ['Woezel & Pip Op zoek naar de Sloddervos!', 'The White Snake',
        'Proof of Life', 'Rise of the Planet of the Apes',
        'Mona Lisa Smile', '2 Guns', 'Max Payne', 'De eetclub']

for item in film:
    button = Button(master=aanbiederspage, text=item, 
                    command=filmdatabase).pack()

Upvotes: 2

Views: 1925

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55499

The simple way to do this is to pass the item string to the command callback, but you have to be careful how you do this. One way is to make the item string a default arg to a lambda function. It has to be a default arg so that item gets bound to that arg when the lambda is defined. If we just did lambda : func(item) then every button would print the last item in the list. That happens because in that case Python looks up the current value of item when the callback is called.

import tkinter as tk

film = ['Woezel & Pip Op zoek naar de Sloddervos!', 'The White Snake',
    'Proof of Life', 'Rise of the Planet of the Apes', 'Mona Lisa Smile', 
    '2 Guns', 'Max Payne', 'De eetclub']

def func(item):
    print(item)

root = tk.Tk()

for item in film:
    tk.Button(master=root, text=item, command=lambda s=item: func(s)).pack()

root.mainloop()

Note how in my code I don't do button = tk.Button(... There's no point making that assignment. Firstly, we aren't saving those widgets anywhere, but more importantly, .pack returns None, so doing

button = Button(master=aanbiederspage, text=item, command=filmdatabase).pack()

actually sets button to None, not to the Button widget.

Upvotes: 3

Keith Cargill
Keith Cargill

Reputation: 82

You can use lambda with command to send arguments to 'filmdatabase': it should look something like this:

for item in film:
    button = Button(master=aanbiederspage, text=item, command= lambda: filmdatabase(item)).pack()

Upvotes: -1

Related Questions