简体   繁体   中英

Looping over a dictionary to make Tkinter buttons, issue with Command on button click

I am trying to make a GUI application to work with the Philips hue API using Python and Tkinter. Currently I have a dictionary of python objects, of which is being looped over to create a button for each object, ie the button text has the item or light name for example.

The issue comes when I am using the command statement. Each button has the command function, which contains the function I would like to be called upon button click.

The button are made fine, with the correct text values in them, but the issue comes when I click on the button, and the function regarding the object is called (called itemClick in this case), it passes the object that should be on the last button, or at the end of the loop.

I've tried using the 'bind' function on the button, but in this case the button was clicked for the amount of times that the loop went through.


lightsButtonDict = {}
for item in lightlist:
    print(lightlist[item].getName())
    lightsButtonDict[lightlist[item].getName()] = tk.Button(lightsFrame, text=lightlist[item].getName(), command=lambda: itemClick(lightsFrame, 'light', lightlist[item]))
    lightsButtonDict[lightlist[item].getName()].pack()

Where I declare command = lambda: itemClick(lightsFrame, 'light', lightslist[item])

upon button click the last lightlist[item] will be passed into the function, not the one on the loop, ie if there are 10 buttons, and you click the 3rd one, the 10th object will be passed into itemClick (sorry if that sounds a bit jumbled up, hopefully it's understandable)

I'd like to pass in the object that is related to that current loop, so if the 3rd button is clicked then the 3rd object is passed in and so on.

TIA.

lambda will store the item in the iteration if you assign it to a variable in the call:

lightsButtonDict = {}
for item in lightlist:
    print(lightlist[item].getName())
    lightsButtonDict[lightlist[item].getName()] = tk.Button(lightsFrame, 
    text=lightlist[item].getName(), 
    command = lambda i = lightslist[item]: itemClick(lightsFrame, 'light', i).pack()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM