我的代码是什么问题?它应该在画布中显示所选图像

时间:2017-05-09 20:51:31

标签: python canvas tkinter

import tkinter as tk
from tkinter import *
from PIL import Image,ImageTk
from PIL import ImageTk
from tkinter import filedialog
import sys
# # # 
root=tk.Tk()
root.geometry('1000x690')
root.title("Baccalauréat ISN 2017")

def Open_Image():
    Im =Image.open(filedialog.askopenfilename())

# i want to be able to resize the image without deforming it.
    Nim = Im.resize((int((Im.width*514)/Im.height), 514))   #maxsize =     (821, 514) ---> size of the canvas 821-length; 514 -height
    nshow = ImageTk.PhotoImage(Nim)

    Can = tk.Canvas(root, background = 'blue')
    Can.grid(row = 1, column = 0, rowspan = 6, columnspan = 5, sticky = W + E + N + S)
    Cim = Can.create_image(0, 0,  anchor = NW, image = nshow)

B13= Button(root, text='Open Image', height=5, width= 25, command = Open_Image)
B13.grid(row=1, column=5, sticky= W + E)


mainloop()

为什么代码不起作用?它显示了这个(空白画布),而不是它应该在其位置显示的选定文件。 enter image description here

1 个答案:

答案 0 :(得分:0)

很可能陷入垃圾收集。要防止这种情况,请将其绑定到引用,即在此情况下将root.放在您为图像指定的名称前面或类似的名称前面。