【发布时间】: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循环中。您的代码尝试在每一行的每一列中放置相同的内容。彻底摆脱循环外的那个。