-3

I have programmed software that displays a "tuile".

Definition of a tuile:

A tuile is a Frame which contains a button which displays an image and an explanatory text.

I would like to display 3 tuiles with 3 different settings.

listes_icones = ["icone1.png","icone2.png","icone3.png"]
listes_relx = [".3",".4",".5"]
listes_text = ["SYSTEM", "USER", "GAME"]

for i in range(3):

    gen_img = PhotoImage(file=listes_icones[i])
    gen_cadre = Frame(home,width=100, height=100,bg=bg_root)
    gen_cadre.place(anchor="c", relx=listes_relx[i], rely=.5)

    gen_img_bouton = Button(gen_cadre, image=gen_img, relief="flat",bg=bg_root)
    gen_img_bouton.pack()

    gen_text = Label(gen_cadre, text=listes_text[i], bg=bg_root, fg=text_color,font="blocktastic 18")
    gen_text.pack()

I manage to display the text but not the button and the image, the variable is overwritten. How to solve this problem?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
IIX 61
  • 17
  • 7
  • 2
    Does this answer your question? [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) – Thingamabobs Aug 03 '20 at 16:18

1 Answers1

1

The problem that you are facing is like you said, the variable is overwritten in your loop. To solve this you need to keep track of your generated images. A simple solution is to store them in a list and get them in the next step. Here is an exampel:

import tkinter as tk
import PIL

listes_icones = ["icone1.png","icone2.png","icone3.png"]
gen_icons = []
listes_relx = [".3",".4",".5"]
listes_text = ["SYSTEM", "USER", "GAME"]

home = tk.Tk()



for i in range(3):
    gen_img = tk.PhotoImage(file=listes_icones[i])
    gen_icons.append(gen_img)
    gen_cadre = tk.Frame(home,width=100, height=100)
    gen_cadre.place(anchor="c", relx=listes_relx[i], rely=.5)

    gen_img_bouton = tk.Button(gen_cadre, image=gen_icons[i], relief="flat")
    gen_img_bouton.pack()

    gen_text = tk.Label(gen_cadre, text=listes_text[i], font="blocktastic 18")
    gen_text.pack()

home.mainloop()
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • Hello ! Can we add a command to each button generated ? gen_img_bouton.command(Myfunction) ? – IIX 61 Aug 06 '20 at 17:39
  • Yes we can!. Look into that link https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments – Thingamabobs Aug 06 '20 at 17:42
  • If you intrested in understanding lambda, I wrote this answer here https://stackoverflow.com/questions/16501/what-is-a-lambda-function/62742314#62742314 – Thingamabobs Aug 06 '20 at 17:44