如何在def函数中使用tkinter从url发布图像

时间:2015-04-14 05:13:32

标签: python tkinter

我的问题的标题可能很混乱,但我不知道如何更好地说出来。

基本上当我把我的代码放在def中用于按钮命令时,它不起作用,但代码在def之外工作就好了。

这是不起作用的代码:

app = Tk()
app.geometry("1000x800")

def search():
    tx1get = tx1.get()
    Label(app, text="You Entered: \"" + tx1get + "\"").grid(row=1, column=0)
    fd = urllib.urlopen("http://ia.media-imdb.com/images/M/MV5BMTc2MTU4ODI5MF5BMl5BanBnXkFtZTcwODI2MzAyOA@@._V1_SY317_CR7,0,214,317_AL_.jpg")
    imgFile = io.BytesIO(fd.read())
    im = ImageTk.PhotoImage(Image.open(imgFile))
    image = Label(app, image = im, bg = "blue")
    image.grid(row=2, column=0)

tx1=StringVar()
tf = Entry(app, textvariable=tx1, width="100")
b1 = Button(app, text="Search", command=search, width="10")
tf.grid(row=0, column=0)
b1.grid(row=0, column=1)

app.mainloop()

但是如果我删除def中的最后5行并将它们放在def之外,它就可以工作:

app = Tk()
app.geometry("1000x800")

def search():
    tx1get = tx1.get()
    Label(app, text="You Entered: \"" + tx1get + "\"").grid(row=1, column=0)

tx1=StringVar()
tf = Entry(app, textvariable=tx1, width="100")
b1 = Button(app, text="Search", command=search, width="10")
tf.grid(row=0, column=0)
b1.grid(row=0, column=1)

fd = urllib.urlopen("http://ia.media-imdb.com/images/M/MV5BMTc2MTU4ODI5MF5BMl5BanBnXkFtZTcwODI2MzAyOA@@._V1_SY317_CR7,0,214,317_AL_.jpg")
imgFile = io.BytesIO(fd.read())
im = ImageTk.PhotoImage(Image.open(imgFile))
image = Label(app, image = im, bg = "blue")
image.grid(row=2, column=0)

app.mainloop()

非常感谢任何帮助或建议!

1 个答案:

答案 0 :(得分:1)

您的代码不起作用,因为im中的searchsearch完成后超出范围。这样,您的ImageTk对象也会消失。为防止这种情况,请将im全局(一种可能的解决方案):

import urllib 
from Tkinter import *
import io
from PIL import Image, ImageTk


app = Tk()
app.geometry("1000x800")

im = None  #<-- im is global

def search():
    global im  #<-- declar im as global, so that you can write to it
               # not needed if you only want to read from global variable.
    tx1get = tx1.get()
    Label(app, text="You Entered: \"" + tx1get + "\"").grid(row=1, column=0)
    fd = urllib.urlopen("http://ia.media-imdb.com/images/M/MV5BMTc2MTU4ODI5MF5BMl5BanBnXkFtZTcwODI2MzAyOA@@._V1_SY317_CR7,0,214,317_AL_.jpg")
    imgFile = io.BytesIO(fd.read())
    im = ImageTk.PhotoImage(Image.open(imgFile))
    image = Label(app, image = im, bg = "blue")
    image.grid(row=2, column=0)

tx1=StringVar()
tf = Entry(app, textvariable=tx1, width="100")
b1 = Button(app, text="Search", command=search, width="10")
tf.grid(row=0, column=0)
b1.grid(row=0, column=1)

app.mainloop()