【问题标题】:tkinter.TclError: image "pyimage" doesn't exist with Button wrapper classtkinter.TclError:图像“pyimage”不存在按钮包装类
【发布时间】:2020-05-25 16:16:57
【问题描述】:

Tkinter 的一个常见问题是,为了在标签和按钮中使用图像,您需要以某种方式引用 PhotoImage 对象。

我已经围绕 Button 编写了一个包装类来添加我自己的功能,因为我想使用 GIF 而不是图像,并且我希望能够在按下按钮时在 gif 之间切换(或使用 keyboard 热键)。第一个 GIF 运行良好并且循环完美。当我切换到第二个 GIF 时,我收到错误消息,说 _tkinter.TclError: image "pyimage48 ... pyimage55" doesn't exist。如下所示:

from tkinter import *
from PIL import ImageTk, Image

class AnimatedButton(Button)
  def __init__(self, master, size, img_paths):
    self.size = size
    self.seq_count = len(img_paths) # Number of gif files
    self.sequences = []

    for path in img_paths:
      gif, delay = loadGif(path)
      # Create a tuple of all frames in a gif, with the delay between frames. Store this tuple in self.sequences
      self.sequences.append(([ImageTk.PhotoImage(frame) for frame in gif], delay))

    self.delay = self.sequences[0][1]
    self.current_sequence = self.sequences[0][0]
    self.image = self.current_sequence[0]

    self.seq_id = 0 # Sequence counter
    self.frame_id = 0 # Frame counter
    Button.__init__(self, master, image=self.image, width=size, height=size)
    self.cancel = self.after(self.delay, self.play)

  def play(self):
    self.image = self.current_sequence[self.frame_id]
    self.config(image=self.image)
    # More stuff below to loop through the frames etc.

奇怪的是,我的另一个 Button 类 MyButton 也没有这些,它也是一个包装类。

class MyButton(Button):
    def __init__(self, master, size, img_paths):
        self.image_count = len(img_paths)
        self.image_id = 0
        self.size = size

        self.images = []
        for path in img_paths:
            try:
                im = Image.open(path)
            except:
                print("Could not open file {}".format(path))
            photo_image = ImageTk.PhotoImage(im, image_mode)
            self.images.append(photo_image)
        self.image = self.images[0]

        Button.__init__(self, master, image=self.image, width=size,
                        height=size)

大多数 Google 搜索结果表明您不应该使用两个 tkinter.Tk() 调用,但我只使用一个(是的,我确定了)。

非常感谢任何想法!

【问题讨论】:

  • 请提供Minimal, Complete, and Verifiable example。为什么?因为我们运行代码是为了分析它,如果我们必须编写自己的代码来运行它可能与您正在运行的代码不同。
  • 您创建了一个listlist.append(([ImageTk.PhotoImage(frame) for ...,应仅是list
  • @stovfl 这是设计使然。我存储多个帧的多个序列,即列表列表。
  • 这是设计使然:好的,但是你不能访问 one 图像:self.current_sequence[0]因为这会返回 list 的图像。
  • @figbeam 这几乎是不可能的。整个程序是一个大管道。可能不是好习惯,但我是新人,这就是我在这里的原因。

标签: python tkinter python-imaging-library


【解决方案1】:

感谢上面 cmets 中 stovfl 的提示,我在 play() 中丢失了 [0]

正确的代码应该是:

def play(self):
    self.image = self.current_sequence[self.frame_id][0]
    self.config(image=self.image)
    # More stuff below to loop through the frames etc.

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 2013-12-13
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2018-02-03
    相关资源
    最近更新 更多