Home > OS >  Create Enum referencing a list with TkImages
Create Enum referencing a list with TkImages

Time:04-08

I've got a couple of images in a folder and each of these gets resized and turned into an image for Tkinter. I want to use these images in other python scripts as a enum.

This is how I create the images:

import os
from PIL import Image, ImageTk
from enum import Enum

#Resize All Images and turn them into TkImages
def ResizeImages():
    PieceImages = []
    for images in os.listdir('Resources'):
        cImage = Image.open('Resources/'   images)
        cImage = cImage.resize((80, 80), Image.ANTIALIAS)
        PieceImages.append(ImageTk.PhotoImage(cImage))
    return PieceImages

#Called from outside to create PNGS list AFTER Tkinter.Tk() was called
def InitializeImages():
    global PNGS
    PNGS = ResizeImages()


#This is the part where I'm lost
class Black(Enum):
    global PNGS
    Queen = PNGS[3]
    King = PNGS[4]
    Tower = PNGS[5]

I want to create a Tkinter Button with these images on like this:

#PieceImages is the .py file above
import PieceImages import Black
form tkinter import *
root = Tk()
root.geometry('800x800')
someButton = tk.Button(root, image=Black.Tower).place(x=100, y=100)

My Question is:
Is it even possible to create enums of this type and if so, how?

CodePudding user response:

I'd recommend staying away from global variables; you can pass arguments to a class directly:

class Black():
    def __init__(self, pngs):
        self.name1 = pngs[0]
        self.name2 = pngs[1]

Instantiate by passing pngs:

black = Black(pngs)

Then black.name1, black.name2 etc will be your desired images.

  • Related