Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

python - How to update an image on a Canvas?

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, columnspan = 3)
MyImage = PhotoImage(file = "sample1.gif")
camelot.create_image(0, 0, anchor = NW, image = MyImage)

This is run at the beginning. What I want to do on later in another function is replace "sample1.gif" by "sample2.gif", and, possibly later on, replace that in turn by "sample3.gif". I'm stuck and nothing I've been trying has worked so far.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...