python,在tkinter中显示图像的功能?

时间:2015-12-30 17:57:58

标签: python function tkinter

我想创建一个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 

你知道我做错了吗?

2 个答案:

答案 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 = &num;

    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个变量,photowimgShow的本地变量。一种解决方法是返回对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)