如何更新画布上的图像? [英] How to update an image on a Canvas?

查看:76
本文介绍了如何更新画布上的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到问题的代码的本质:

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)

这是在开始时运行的.我稍后想在另一个函数中做的是将 "sample1.gif" 替换为 "sample2.gif",并且可能稍后将其替换为 <代码>sample3.gif".我被卡住了,到目前为止我一直在尝试的任何东西都没有奏效.

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.

推荐答案

将图像添加到画布:

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

更改图片:

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

完整示例:

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()

示例中使用的图像:

ball1.gif ball2.gif ball3.gif

ball1.gif ball2.gif ball3.gif

结果:

这篇关于如何更新画布上的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆