【问题标题】:tkinter canvas image is not displayed in classtkinter 画布图像未显示在课堂上
【发布时间】:2013-05-26 15:16:40
【问题描述】:

我正在尝试使用 tkinter 画布选项在 python 中显示图像。但是,如果我在一个类中输入它,如下所示,它不会给出错误但也不会显示我的图像。但按钮显示正确。此外,如果我将生成此图像的代码从类中取出,它可以正常工作。我似乎无法找出问题所在。

import Tkinter as tk
from Tkinter import *

class Board(tk.Frame):
    def __init__(self,parent):

        frame = Frame(parent)
        frame.pack()
        tk.Frame.__init__(self,parent)

        frame2 = Frame(frame)
        frame2.pack()

        c=Canvas(frame2)
        c.pack(expand=YES,fill=BOTH)
        background=PhotoImage(file='Board.gif')
        c.create_image(100,100,image=background,anchor='nw')

        button = Button(frame, text="Next turn", command=self.next_turn)
        button.pack()

        button = Button(frame, text="Roll the dice", command=self.roll)
        button.pack()

        ....

root = Tk()
board = Board(root)
board.pack()
root.mainloop()

【问题讨论】:

  • 你为什么同时做import Tkinter as tkfrom Tkinter import *
  • 我的老师告诉我这样做,以确保所有东西都被导入或其他东西。我知道这不是必要的,但现在有些行有 tk.'something' 如果我只是删除 tk.我的程序吓坏了。你认为这可能是问题所在?
  • 这可能是因为tk.Frame.__init__(self,parent)class Board(tk.Frame)。您可以将其更改为Frame.__init__(self,parent)class Board(Frame),这应该可以,但我不确定您为什么直接调用__init__ 方法;我也看不出 Frame 有什么用途,因为您没有继续引用它。

标签: python tkinter


【解决方案1】:

您必须保留对 PhotoImage 的引用。这只是示例(您也可以使用self.background 而不是c.background):

    c = Canvas(frame2)
    c.pack(expand=YES,fill=BOTH)
    c.background = PhotoImage(file='Board.gif')
    c.create_image(100,100,image=c.background,anchor='nw')

【讨论】:

  • 非常感谢!这解决了问题,实在找不到。
  • @user2438352 不客气,很高兴为您提供帮助;)如果它解决了您的问题,请随时接受答案。
  • 知道为什么Canvas.create_image() 会增加它传递的image= 的引用计数,这样它就不会在函数返回时被破坏?似乎它应该根据通常的 Python 的内存管理规则。
  • 同样,为什么在c 中添加对它的引用会起作用,因为c 也是一个局部变量?
  • @martineau 我想这可能会回答你的问题:effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 2012-12-28
  • 2014-12-16
相关资源
最近更新 更多