How to update an image on a Canvas?

后端 未结 2 538
滥情空心
滥情空心 2020-11-29 05:39

This is the essence of the code I\'m having trouble with:

camelot = Canvas(main, width = 400, height = 300)
camelot.grid(row = 0, column = 0, rowspan = 11,          


        
相关标签:
2条回答
  • 2020-11-29 06:11

    Add image to canvas:

    self.image_on_canvas = self.canvas.create_image(0, 0, image = ...)

    Change image:

    self.canvas.itemconfig(self.image_on_canvas, image = ...)


    Full example:

    from Tkinter import *
    
    #----------------------------------------------------------------------
    
    class MainWindow():
    
        #----------------
    
        def __init__(self, main):
    
            # canvas for image
            self.canvas = Canvas(main, width=60, height=60)
            self.canvas.grid(row=0, column=0)
    
            # images
            self.my_images = []
            self.my_images.append(PhotoImage(file = "ball1.gif"))
            self.my_images.append(PhotoImage(file = "ball2.gif"))
            self.my_images.append(PhotoImage(file = "ball3.gif"))
            self.my_image_number = 0
    
            # set first image on canvas
            self.image_on_canvas = self.canvas.create_image(0, 0, anchor = NW, image = self.my_images[self.my_image_number])
    
            # button to change image
            self.button = Button(main, text="Change", command=self.onButton)
            self.button.grid(row=1, column=0)
    
        #----------------
    
        def onButton(self):
    
            # next image
            self.my_image_number += 1
    
            # return to first image
            if self.my_image_number == len(self.my_images):
                self.my_image_number = 0
    
            # change image
            self.canvas.itemconfig(self.image_on_canvas, image = self.my_images[self.my_image_number])
    
    #----------------------------------------------------------------------
    
    root = Tk()
    MainWindow(root)
    root.mainloop()
    

    Images used in example:

    ball1.gif ball1.gif ball2.gif ball2.gif ball3.gif ball3.gif

    Result:

    0 讨论(0)
  • 2020-11-29 06:15
        MyImage = PhotoImage(file = "sample1.gif")
        labelorbuttontodisplayit.image = MyImage
        labelorbuttontodisplayit.configure(image=MyImage)
    

    :P that should do it. I only tried to use that code on label or buttons, never as a Canvas, but i guess you can adapt that piece of code a bit.

    0 讨论(0)
提交回复
热议问题