On 2019-07-07 19:28, Abdur-Rahmaan Janhangeer wrote:
Greetings, i have this snippet:
---
import json
import os
from tkinter import *
from tkinter.ttk import *

root = Tk()
jload = json.load
buttons = list()
programs = os.listdir('programs')
for i, program in enumerate(programs):
     jsonpath = 'programs/{}/cmdlaunch.json'.format(program)
     info = jload(open(jsonpath))
     photo = PhotoImage(file = 'icons/'+info['icon'])
     photoimage = photo.subsample(3, 3)
     buttons.append(Button(root, text = 'Click Me !', image = photoimage,
                         compound = LEFT))
     buttons[-1].pack()

root.mainloop()
---

All buttons are appearing but only the last button is displaying the image,
any idea?

You need to keep a reference to the image that you passed when creating the button; tkinter itself doesn't keep a reference to it:

import json
import os
from tkinter import *
from tkinter.ttk import *

root = Tk()
jload = json.load
buttons = list()
images = []
programs = os.listdir('programs')

for i, program in enumerate(programs):
     jsonpath = 'programs/{}/cmdlaunch.json'.format(program)
     info = jload(open(jsonpath))
     photo = PhotoImage(file = 'icons/'+info['icon'])
     photoimage = photo.subsample(3, 3)
     buttons.append(Button(root, text = 'Click Me !', image = photoimage,
                         compound = LEFT))
     buttons[-1].pack()
     images.append(photoimage)

root.mainloop()

In your code, 'photoimage' still refers to the last image, but there are no references to the previous images, so they're discarded.

(Why is tkinter like that? Who knows! :-))
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to