python,在tkinter中显示图像的函数? [英] python, function that shows image in tkinter?
本文介绍了python,在tkinter中显示图像的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个 tkinter 窗口并显示 lena 图片.我有一个有效的代码,但我不知道如何利用它来制作一个功能.
i want to create a tkinter window and display the lena picture. I got a code that is working but i dont know how to make a function out of it.
代码:
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的图片...:
I tried this function but it didnt open the lena picture...:
#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
你知道我做错了什么吗?
Do you know what i am doing wrong?
推荐答案
PhotoImage
分配给函数中的局部变量存在众所周知的问题.Garbage Collector
在您离开函数时移除图像,但您可以像这样将 photo
(例如)分配给 w
:
There is well known problem with PhotoImage
assigned to local variable in function. Garbage Collector
remove image when you leave function but you can assign photo
(for example) to w
like this:
photo = ImageTk.PhotoImage(image)
w = Canvas(root)
w.photo = photo # assign photo to object.
这篇关于python,在tkinter中显示图像的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文