用于在tkinter画布上放置图像的生成器

时间:2017-07-10 16:46:44

标签: python tkinter generator

我有大约90张图片的路径列表,现在我想将它们全部放在canva上,但只允许说30个在一个“行”中,但如果我使用

from tkinter import * 

def createCanvaImages(paths):
paths = ['list with the paths']
mainWin = Tk()
canva = Canvas(mainWin, width = 900, height = 300).pack()
for x in range(0, len(paths),):
    if x <= 30: #not sure if this places only 30 in one row
        y=x/3
    elif x > 30
        y=(x+24)/3
    elif x >= 60
        y=(x+48)/3
    img = PhotoImage(file = paths[x])
    canva.create_image(x+24, y, image = img)

 mainWin.mainloop()

它只显示最后一条路径的图像

修改

现在显示画布上的所有图像(如果画布不在画面中)(感谢Novel)但如果canva在画面中则不起作用

from tkinter import * 

def createImagePaths(dct):
    paths=[]
    for i in range(len(masteries)):

        if dct.get(masteries[i]) == 0:
            file = masteries[i]+'.png'
            path = os.path.join(path_gray, file)
            paths.append(path)
            #create canvas image fnc
        if dct.get(masteries[i]) != 0:
            file = masteries[i]+'.png'
            path = os.path.join(path_colored, file)
            paths.append(path)

    return createCanvaImages(paths)

def createCanvaImages(paths):
    img_refs = []
    canva = Canvas(masteryFrame, height = 400).pack()
    for i, path in enumerate(paths):
            col,row = divmod(i,30)
            img = PhotoImage(file=path)
            canva.create_image( row*24, col*24, image = img, anchor = 'nw')
            img_refs.append(img)

root = Tk()
mainFrame = Frame(root)
mainFrame.grid(column=0,row=0, sticky=(N,W,E,S))

masteryFrame = Frame(root)
masteryFrame.grid(row=1,column=0, sticky=(N,W,E,S))

root.mainloop()

1 个答案:

答案 0 :(得分:1)

您需要保存图像参考。最简单的方法是将它们添加到列表中。猜猜:

from tkinter import * 

def createCanvaImages(paths):
    canva = Canvas(masteryFrame, width = 900, height = 300)
    canva.pack()
    canva.img_refs = []
    for i, path in enumerate(paths):
        row, col = divmod(i, 30)
        img = PhotoImage(file = path)
        canva.create_image(col*24, row*24, image = img, anchor='nw') # each image is 24x24
        canva.img_refs.append(img)

此外,请确保您从未将窗口小部件初始化和布局放在同一行上。 IOW,不要这样做:Widget(master).pack()。总是把它们分开。

您还应该尽快了解OOP和课程。使用函数来构建这样的UI将非常快速地变得非常混乱和错误。