18

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

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"。我被困住了,到目前为止我一直在尝试的任何事情都没有奏效。

4

2 回答 2

36

将图像添加到画布:

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

示例中使用的图像:

球1.gif球1.gif球2.gif球球2.gif3.gif球3.gif

结果:

在此处输入图像描述

于 2013-11-07T17:29:36.990 回答
2
    MyImage = PhotoImage(file = "sample1.gif")
    labelorbuttontodisplayit.image = MyImage
    labelorbuttontodisplayit.configure(image=MyImage)

:P 应该这样做。我只尝试在标签或按钮上使用该代码,而不是作为画布,但我想你可以稍微调整一下这段代码。

于 2013-11-07T15:02:04.787 回答