【问题标题】:Tkinter - Scan and list all the images in a folder and load themTkinter - 扫描并列出文件夹中的所有图像并加载它们
【发布时间】:2021-05-08 09:13:06
【问题描述】:

我正在尝试使用 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] Permission denied: './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 个单选按钮)。

我做错了什么?

最好, 多纳泰罗

【问题讨论】:

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

标签: python tkinter


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多