Reputation: 49
In my program, I am creating many images on the canvas, however, I feel that the way I am currently doing it is inefficient and repetitive. Here is the basic structure of the program:
import tkinter as tk
from PIL import Image, ImageTk
CANVAS_IMG = ['image1', 'image2', 'image3', 'image4']
class MyApp:
def __init__(self, parent):
self.parent = parent
self.canvas_img = {item: ImageTk.PhotoImage(file=f'img/{item}.png') for item in CANVAS_IMG}
self.canvas.create_image(485, 370, image=self.canvas_img['image1'])
self.canvas.create_image(490, 360, image=self.canvas_img['image2'])
self.canvas.create_image(350, 55, image=self.canvas_img['image3'])
self.canvas.create_image(720, 375, image=self.canvas_img['image4'])
if __name__ == '__main__':
root = tk.Tk()
MyApp(root)
root.mainloop()
The coordinates of the images don't follow any kind of pattern.
I have thought about creating a list of tuples to store the coordinates for the images, but that seems kind of clunky. What would you recommend as the best way to do this?
Upvotes: 0
Views: 1341
Reputation: 385970
One way would be to create a dictionary where the keys are the image names and the values are the coordinates:
IMAGE_DATA = {
"image1": (485, 370),
"image2": (490, 360),
...
}
You can then easily loop over the dictionary to create the images.
Upvotes: 2