Python Tkinter-扫描并列出文件夹中的所有图像并加载它们

Python Tkinter-扫描并列出文件夹中的所有图像并加载它们,python,tkinter,Python,Tkinter,我正试图设计一个与Tkinter的MAME游戏的关卡编辑器。 在一个文件夹中,我有256个要处理的图像,并将它们用作Radiobutton图像 现在我正在一个接一个地加载它们,以便像这样使用它们: img_00 = PhotoImage(file="./gfx/00.png") img_01 = PhotoImage(file="./gfx/01.png") img_02 = PhotoImage(file="./gfx/02.png"

我正试图设计一个与Tkinter的MAME游戏的关卡编辑器。 在一个文件夹中,我有256个要处理的图像,并将它们用作Radiobutton图像

现在我正在一个接一个地加载它们,以便像这样使用它们:

img_00 = PhotoImage(file="./gfx/00.png")
img_01 = PhotoImage(file="./gfx/01.png")
img_02 = PhotoImage(file="./gfx/02.png")
等等

即使我是一个初学者,我知道这个方法是有效的,但它不是一个好的实践。 我想用for循环加载它们,但无法对其进行编码

我试过了

img_list=[]
my_folder= os.listdir('gfx/')
img=PhotoImage(Image.open('./gfx/'))
n_row = 0
n_col= 0

for x in my_folder:
    n_col +=1
    if n_col > 16:
        n_row +=1
        n_col = 1
    img_list.append(img)
    radio_button = Radiobutton(C, image=img, indicatoron=0)
    radio_button.grid(row=n_row, column=n_col)
我得到:PermissionError:[Errno 13]权限被拒绝:'./gfx/'

我还测试了:

img_list=[]
my_folder= os.listdir('gfx/')
img=PhotoImage() ################ no path to folder ##############
n_row = 0
n_col= 0

for x in my_folder:
    n_col +=1
    if n_col > 16:
        n_row +=1
        n_col = 1
    img_list.append(img)
    radio_button = Radiobutton(C, image=img, indicatoron=1)
    radio_button.grid(row=n_row, column=n_col)
没有加载图像,但我获得了256个单选按钮,这与我想要使用的图像数量相对应(我还尝试从文件夹中删除一个图像,获得了255个单选按钮)

我做错了什么

最好的,
Donatello

到目前为止,我有以下代码:

img_list = []
n_row = 0
n_col= 0
i=0

for name in glob.glob(r'gfx/*'):
    img = PhotoImage(name)
    val = img
    img_list.append(val)
    i+=1
    
    n_col +=1    
    if n_col > 16:
        n_row +=1
        n_col = 1    
    
    radio_button = Radiobutton(C, image=img_list[i-1], indicatoron=0)
    radio_button.grid(row=n_row, column=n_col)
我没有得到任何错误,我得到了我的256个按钮,但图像仍然没有加载。
我肯定错过了一些东西。

我发布了我找到的解决方案

img_list=[]
path = "./gfx" # my folder
n_row = 0
n_col = 0
index = 0
x = IntVar()
for f in os.listdir(path):
    img_list.append(ImageTk.PhotoImage(Image.open(os.path.join(path,f))))
    n_col +=1
    index +=1
    if n_col > 9:
        n_row +=1
        n_col = 1
    radio_button = Radiobutton(C, image=img_list[index-1], indicatoron=0, bd=2, variable = x, value = index)
    radio_button.grid(row=n_row, column = n_col)

在循环中,您需要为文件夹中的每个图像文件创建一个单独的
PhotoImage
,并将其附加到每个
Radiobutton
。不要试图将每个变量存储在不同名称的变量中,而是将它们全部存储在一个列表中。嗨。谢谢你的回复。“为文件夹中的每个图像文件创建单独的照片图像”是什么意思?我的意思是在
for
循环中为每个名为
x
的图像文件创建一个新的照片图像。代码尝试在每行的每一列中放置相同的代码。完全摆脱循环之外的循环。