0

Following Problem, im generating Buttons from a list with globals(). For each button there should be a function behind it that runs with the 'at that time' given args. For that im using lambda to give args to the function...

How the Buttons are created:

counter = 0
if len(match_id_list) >= 14:
    for i in range(1, 4):
        for j in range(1, 6):
            match_map, \
            match_timestamp, \
            match_gamemode, \
            match_duration, \
            match_player_kills, \
            match_telemetry_id, \
            match_telemetry_url = Player.match_search(match_id_list[counter], player_id)

            globals()[counter] = Button(player_matches_frame, text=f'{match_map} | {match_gamemode} | {match_player_kills} Kill/s',
                                        width=100, height=3)
            globals()[counter].grid(column=i, row=j, padx=10, pady=10)
            counter += 1

When i add a command with specific args to each Button it looks like this:

globals()[counter] = Button(player_matches_frame, text=f'{match_map} | {match_gamemode} | {match_player_kills} Kill/s',
                                        width=100, height=3, command=lambda: match_analysis(match_telemetry_id, match_telemetry_url))

It should use the variables that were created for that instance, but what it takes is the Last given ones. Im not sure if thats because the command arg or the lambda. Anyway, is there maybe a fix or a better way to solve it?

Code for Testing / Reproducing:

from tkinter import *

id_list = ["000", "001", "002", "003", "004"]
url = ["000.com", "001.com", "002.com", "003.com", "004.com"]

def match_analysis(url):
    print(url)

root = Tk()
root.geometry("700x700")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.rowconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
root.rowconfigure(3, weight=1)
root.rowconfigure(4, weight=1)

for i in range(len(id_list)):
    globals()[i] = Button(root, text=id_list[i], command=lambda: match_analysis(url[i]))
    globals()[i].grid(column=0, row=i, padx=5, pady=5)

root.mainloop()
LiiVion
  • 312
  • 1
  • 10
  • 1
    (1) Using "globals()" in this way is bad style, create an own list or dict to store the buttons. (2) Replace the lambda by something like `lambda tid=match_telemetry_id, turl=match_telemetry_url: match_analysis(tid, turl)`. Storing the values in parameter defaults is the usual approach. – Michael Butscher Sep 29 '22 at 06:51
  • Jep, it works with the lambda parameters, i will also try to create buttons with a list later on. Thanks for the fast Help! – LiiVion Sep 29 '22 at 07:01

0 Answers0