tkinter 画布图像不显示 [英] tkinter canvas image not displaying

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

问题描述

我在一个函数中创建了一个简单的画布,我想在画布上显示一个图像.

I have a simple canvas being created in a function, and i would like an image displayed on the canvas.

def start(root):
    startframe = tkinter.Frame(root)
    canvas = tkinter.Canvas(startframe,width=1280,height=720)

    startframe.pack()
    canvas.pack()

    one = tkinter.PhotoImage('images\one.gif')
    canvas.create_image((0,0),image=one,anchor='nw')

当我运行代码时,我得到一个空白的 1280x720 窗口,没有图像.

when i run the code i get a blank 1280x720 window, no image.

我查看了以下网站:http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm 但我不明白如何将他们的例子应用于我的情况(我不知道如何创建对或如何创建参考,如果这是我的问题).我还查看了一些堆栈溢出问题,但它们也没有帮助.

i have looked at the following website: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm but i do not understand how to apply their example to my situation (i dont know what to create a reference to or how to create a reference, if that is my problem). I have also looked at some stack overflow questions but they did not help either.

推荐答案

  1. 正确转义路径字符串中的反斜杠.(或使用 r'raw string literal').

防止 PhotoImage 对象被垃圾收集.

Prevent PhotoImage object being garbage collected.

使用 file=... 选项指定文件名.

specify the filename using file=... option.

<小时>

def start(root):
    startframe = tkinter.Frame(root)
    canvas = tkinter.Canvas(startframe,width=1280,height=720)

    startframe.pack()
    canvas.pack()

    # Escape / raw string literal
    one = tkinter.PhotoImage(file=r'images\one.gif')
    root.one = one  # to prevent the image garbage collected.
    canvas.create_image((0,0), image=one, anchor='nw')

更新

one = ...root.one = one 两条语句可以合并为一条语句:

The two statements one = ... and root.one = one can be merged into one statement:

    root.one = one = tkinter.PhotoImage(r'images\one.gif')

这篇关于tkinter 画布图像不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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