我想创建一个tkinter窗口并显示lena图片。我得到了一个有效的代码,但我不知道如何使用它来创建一个函数。
代码:
import numpy
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import scipy.misc
#create root window
root = Tk()
root.geometry("600x600")
#path to lena picture
lena = "C:\lena.jpg"
##------------this as function----------------------------
#convert lena.jpg into tkinter photo image
image = Image.open(lena)
photo = ImageTk.PhotoImage(image)
#create canvas to display picture
w = Canvas(root)
w.create_image(0, 0, image = photo, anchor = "nw")
w.pack(fill = BOTH, expand = YES)
##-------end:-this as function----------------------------
#start root window
root.mainloop()
我试过这个功能,但它没有打开lena图片......:
#create root window
root = Tk()
root.geometry("600x600")
#path to lena picture
lena = "C:\lena.jpg"
def imgShow(img):
##------------this as function----------------------------
#convert lena.jpg into tkinter photo image
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
#create canvas to display picture
w = Canvas(root)
w.create_image(0, 0, image = photo, anchor = "nw")
w.pack(fill = BOTH, expand = YES)
##-------end:-this as function----------------------------
##use function with lena image path.
## doesnt work: window pops up but lena image is not shown
imgShow(lena)
#start root window
root.mainloop()
## ErrorMessages?: No Error Message
你知道我做错了吗?
答案 0 :(得分:3)
在函数中分配给局部变量的PhotoImage
存在众所周知的问题。当您离开函数时Garbage Collector
删除图片,但您可以photo
(例如)将w
分配给photo = ImageTk.PhotoImage(image)
w = Canvas(root)
w.photo = photo # assign photo to object.
,如下所示:
#include <stdio.h>
int main(void) {
int num = 0;
int *pi = #
printf("Address of num: %d Value: %d\n", &num, num);
printf("Address of pi: %d Value: %d\n", &pi, pi);
return 0x0;
}
答案 1 :(得分:0)
原因是local
个变量,photo
和w
是imgShow
的本地变量。一种解决方法是返回对photo
:
def imgShow(img):
##------------this as function----------------------------
#convert lena.jpg into tkinter photo image
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
return photo
#create canvas to display picture
w = Canvas(root)
pic = imgShow(lena)
w.create_image(0, 0, image = pic, anchor = "nw")
w.pack(fill = BOTH, expand = YES)