簡體   English   中英

tkinter canvas 圖像未顯示

[英]tkinter canvas image not displaying

我在 function 中創建了一個簡單的 canvas,我想在 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 window,沒有圖像。

我查看了以下網站:http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm但我不明白如何將他們的示例應用於我的情況(我不知道如果這是我的問題,要創建什么引用或如何創建引用)。 我還查看了一些堆棧溢出問題,但它們也沒有幫助。

  1. 正確轉義路徑字符串中的反斜杠。 (或使用r'raw string literal' )。

  2. 防止 PhotoImage 對象被垃圾收集。

  3. 使用file=...選項指定文件名。


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可以合並為一個語句:

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

canvas.update()怎么樣? 我遇到了類似的問題。 我使用的網格,所以不是.pack我需要使用.update

當我在 function 中調用它時,我遇到了圖像沒有顯示的情況,但其他一切都很好。 那是我的 function

def ask_for_file():
    f_types = [('PNG Images', '*.png')]
    filename = askopenfilename(filetypes=f_types)
    img = ImageTk.PhotoImage(file=filename)
    canvas.config(height=img.height(), width=img.width())
    canvas.create_image(0, 0, anchor=NW, image=img)

我的解決方案是添加img = None作為全局變量並在 function 中更改它。 有效

img = None


def ask_for_file():
    global img
    f_types = [('PNG Images', '*.png')]
    filename = askopenfilename(filetypes=f_types)
    img = ImageTk.PhotoImage(file=filename)
    canvas.config(height=img.height(), width=img.width())
    canvas.create_image(0, 0, anchor=NW, image=img)

    
 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM