我正在尝试使用 Tkinter 为 MAME 游戏设计关卡编辑器。 在一个文件夹中,我有 256 张我想要处理的图像并将它们用作单选按钮图像。
现在我正在一个接一个地加载它们,以便像这样使用它们:
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 个单选按钮)。
我做错了什么?
最好的, 多纳泰罗
答案 0 :(得分:0)
到目前为止我有这个代码:
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 个按钮,但图像仍未加载。 我肯定错过了什么。
答案 1 :(得分:0)
我发布了我找到的解决方案。
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)