2017-05-25 49 views
0

我已經看到了如何使用圖像URL中Tkinter的顯示圖像的例子很多,但沒有這些例子都爲我工作,即如何僅使用標準Python庫在Python 2.7中向Tkinter添加URL圖像?

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/[email protected]@._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() 

當我運行此我得到的錯誤「無模塊名PIL」和在這一個:

from io import BytesIO 
import urllib 
import urllib.request 
import tkinter as tk 
from PIL import Image, ImageTk 
root = tk.Tk() 
url = "http://imgs.xkcd.com/comics/python.png" 
with urllib.request.urlopen(url) as u: 
    raw_data = u.read() 
im = Image.open(BytesIO(raw_data)) 
image = ImageTk.PhotoImage(im) 
label = tk.Label(image=image) 
label.pack() 
root.mainloop() 

我得到「沒有模塊名稱的要求」幾乎所有的例子都使用在其他的PIL模塊的,但我不能讓他們的工作,因爲Python 2.7版不承認很多。我需要顯示一個圖像作爲評估的一部分,並且我們可以導入諸如Tkinter之類的東西,但是該文件需要運行,而無需添加標準Python庫之外的模塊。

值得注意的是,我甚至無法導入「tkinter」。它會說沒有名爲「tkinter」的模塊,因爲它需要以大寫字母「T」開始。

所以我的問題是:

  1. 不PIL需要我安裝其他軟件/庫

  2. 是否「Tkinter的」沒有大寫的「T」不行的進口,因爲我使用Python 2.7?

  3. 使用Python 2.7如何從一個URL

回答

1

這個作品展示在Tkinter的窗口中的圖像,使用python 2.7在Windows上:

from io import BytesIO 
import Tkinter as tk 
import urllib # not urllib.request 
from PIL import Image, ImageTk 

root = tk.Tk() 
url = "http://imgs.xkcd.com/comics/python.png" 

u = urllib.urlopen(url) 
raw_data = u.read() 
u.close() 

im = Image.open(BytesIO(raw_data)) 
image = ImageTk.PhotoImage(im) 
label = tk.Label(image=image) 
label.pack() 
root.mainloop() 

回答您的問題:

  1. 您需要安裝PIL(它在Python 2.7中不是標準的)。
  2. 是的,你需要在Python 2.7中導入Tkinter; tkinter適用於Python 3.x
  3. 您可以使用上面的代碼(只要您安裝PIL)。

此外,

  1. 在Python 2.7,你需要urllib,而不是urllib.request
  2. 似乎所以你需要打開並明確關閉文件,你不能urllib中使用with....open(x) as fname
+0

好的,謝謝你的反饋。我將不得不做它沒有圖像,因爲它是一個任務,我不被允許安裝庫。 – user88720