Jayden Collis
Jayden Collis

Reputation: 155

How do I dynamically set the name of a tkinter label

I have this code in my project:

def savespack():
    savelabelcount = 0
    for i in range(saveamount):
        savelabelcount = savelabelcount + 1
        savebuttontext = "Save " + str(savelabelcount)
        Button(scrollable_frame, text=savebuttontext, width="53", height="5").pack()

The user can create multiple saves in the program, and when the project is reopened, the correct amount of save files will be shown as Tkinter buttons. I've created the buttons by reading a number from an external file. I need to make the buttons have different variable names to call the correct save file and load the correct properties when a button is pressed (for example "Save 2" needs to load save2.txt's properties)

Simply put I need to give Button(scrollable_frame, text=savebuttontext, width="53", height="5").pack() a new variable name for each iteration of the loop, I dont know how to do this. I read something about dictionaries and lists but it was very confusing and I dont know if it can be applied in this situation.

The variable names should be something like: savebutton1, savebutton2, savebutton3 etc.

Any way I could do this would be appreciated, thanks!

Upvotes: 0

Views: 36

Answers (1)

scotty3785
scotty3785

Reputation: 7006

The example below shows how to save each button widget inside a list rather than as separate variables.

It also will call the saveFile function when the button is pressed which currently just prints to the screen the save file number but this function could be replaced with the code that actually saves each file. With this method, it might not even be necessary to keep the buttons in a list.

I'd normally do this using classes rather than globals but this will work for your purposes

import tkinter as tk

saveamount = 5

save_buttons = []

def saveFile(fileNumber):
    print("Saving File ", fileNumber)

def savespack():
    global save_buttons
    savelabelcount = 0
    for i in range(saveamount):
        savelabelcount = savelabelcount + 1
        savebuttontext = "Save " + str(savelabelcount)
        currentButton = tk.Button(scrollable_frame, text=savebuttontext, width="53", height="5")
        currentButton['command'] = lambda x=savelabelcount: saveFile(x)
        currentButton.pack()
        save_buttons.append(currentButton)
        


root = tk.Tk()
scrollable_frame = tk.Frame(root)
scrollable_frame.pack()
savespack()
root.mainloop()

You could use a dictionary rather than a list but given your use case, I'm not sure there is any benefit. Just use save_buttons[2] to access the third button.

Upvotes: 1

Related Questions