Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 图像未显示在tkinter窗口的画布中_Python 3.x_Tkinter_Tkinter Canvas - Fatal编程技术网

Python 3.x 图像未显示在tkinter窗口的画布中

Python 3.x 图像未显示在tkinter窗口的画布中,python-3.x,tkinter,tkinter-canvas,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(r

我试图在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)


您不需要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")