【问题标题】:How can I use images in a tkinter grid?如何在 tkinter 网格中使用图像?
【发布时间】:2017-04-10 14:46:48
【问题描述】:

这是我正在使用的代码。我只是看不到将图像插入网格的位置。我知道fill' is forcolorshould I useimage.open`?如果是这样,它在网格中的位置是什么?

class photo():  # take the photo
    def __init__(self,filename=None):
        with picamera.PiCamera() as cam:
            cam.resolution= (640, 480)
            cam.framerate = 60
            cam.AWB_MODES
            cam.EXPOSURE_MODES
            for effect in cam.IMAGE_EFFECTS:
                cam.image_effect=random
            for i in range(1000):
                cam.capture('/home/pi/Pictures/camFolder/img_%i.jpg')
                time.sleep(2)

class App(tk.Tk):  # build the grid
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.canvas = tk.Canvas(self, width=1000, height=1000, borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top",fill="both", expand="true")
        self.rows= 10
        self.columns =10
        self.cellwidth =100
        self.cellheight =100
        self.rect = {}
        self.oval = {}
        for column in range(20):
            for row in range(20):
                x1 = column*self.cellwidth
                y1= row * self.cellwidth
                x2 = x1 + self.cellwidth
                y2 = y1 + self.cellheight
                self.rect[row,column]= self.canvas.create_rectangle(x1,y1,x2,y2, fill ="blue", tags="rect")
                self.oval[row,column]= self.canvas.create_oval(x1+2,y1+2,x2-2,y2-2, fill="blue", tags="oval")

        self.redraw(1000)

    def redraw(self,delay):
        self.canvas.itemconfig("rect", fill="blue")
        self.canvas.itemconfig("oval", fill="yellow")
        for i in range(10):
            row = random.randint(0,19)
            col = random.randint(0,19)
            item_id = self.oval[row,col]
            self.canvas.itemconfig(item_id, fill="blue")
        self.after(delay, lambda: self.redraw(delay))

if __name__=="__main__":
    app = App()
    app.mainloop()

我是 Python 新手,我一直在学习。

【问题讨论】:

    标签: python tkinter colors grid


    【解决方案1】:

    您应该使用 tkinter 的 PhotoImage 将图像添加到您的程序中。这是一个简短的doc,向您展示如何操作。

    你可以这样使用它:

    from PIL import Image, ImageTk
    
    image = Image.open("lenna.jpg")
    photo = ImageTk.PhotoImage(image)
    
    label = Label(image=photo)
    label.image = photo # this line need to prevent gc
    label.pack()
    

    注意:tkinter 不支持 jpg 或 png 或许多其他类型,您需要使用 PIL 或 Pillow fork,如上所示。唯一受支持的格式是 GIF 和 PGM/PPM,您不需要在其中使用 PIL。

    【讨论】:

    • 您的 effbot.org 链接目前已失效
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 2022-06-27
    相关资源
    最近更新 更多