Tkinter窗口的画布中未显示图像

时间:2019-10-23 04:40:13

标签: python-3.x tkinter tkinter-canvas

我正在尝试在tkinter窗口的画布中显示图像,程序运行正常,但是图像未显示在画布中


import tkinter
from tkinter import *
from tkinter import ttk
import PIL
from PIL import Image,ImageTk

#-----------------------------------------------

root = Tk()
root.geometry("600x400")


toolbox = Frame(root,bg = "#494949",height = 50,width = 600,bd = 1,relief = RAISED)
toolbox.grid(row = 0,column = 0) 
toolbox.grid_propagate(0)

openf = Button(toolbox,text = "Show Image",bg = "gray",width = 30,relief = FLAT,command = lambda:showimg())
openf.grid(row = 0,column =0,sticky = "news")

cj = Canvas(root,width = 600,height = 300,relief = SUNKEN,bd = 1,bg = "#494949")
cj.grid(row = 1,column = 0,sticky = "news")

def showimg():
     g = ImageTk.PhotoImage(file = 'myphoto.png')
     t = cj.create_image(0,0,image = g,anchor = NW)

1 个答案:

答案 0 :(得分:0)

您不需要lambda或PIL,并且需要保留对图像的引用。试试这个:

from tkinter import *
from tkinter import ttk

# functions come first in your code, then you don't need lambda to run them
def showimg():
     g = PhotoImage(file = 'myphoto.png')
     cj.img = g # keep a reference
     cj.create_image(0,0,image = g,anchor = NW)

root = Tk()
root.geometry("600x400")

toolbox = Frame(root,bg = "#494949",height = 50,width = 600,bd = 1,relief = RAISED)
toolbox.grid(row = 0,column = 0) 
toolbox.grid_propagate(0)

openf = Button(toolbox,text = "Show Image",bg = "gray",width = 30,relief = FLAT,command = showimg)
openf.grid(row = 0,column =0,sticky = "news")

cj = Canvas(root,width = 600,height = 300,relief = SUNKEN,bd = 1,bg = "#494949")
cj.grid(row = 1,column = 0,sticky = "news")