2010-07-02 69 views
2

如何創建一個python腳本,該腳本在mac上的目錄中運行圖像(1.jpeg-n.jpeg),並在瀏覽器中或通過另一個python程序顯示它們?Python圖像顯示

我是否將文件導入python並在瀏覽器中顯示? 我是否提取文件名稱1,2,3,4,5並將其添加到列表中,我將該列表提供給另一個調用瀏覽器並顯示的函數?

任何幫助將是偉大的。

謝謝!

回答

5

使用Tkinter和PIL用於此目的非常簡單。添加muskies例如從this thread包含this example信息:

# use a Tkinter label as a panel/frame with a background image 
# note that Tkinter only reads gif and ppm images 
# use the Python Image Library (PIL) for other image formats 
# free from [url]http://www.pythonware.com/products/pil/index.htm[/url] 
# give Tkinter a namespace to avoid conflicts with PIL 
# (they both have a class named Image) 

import Tkinter as tk 
from PIL import Image, ImageTk 

root = tk.Tk() 
root.title('background image') 

# pick an image file you have .bmp .jpg .gif. .png 
# load the file and covert it to a Tkinter image object 
imageFile = "Flowers.jpg" 
image1 = ImageTk.PhotoImage(Image.open(imageFile)) 

# get the image size 
w = image1.width() 
h = image1.height() 

# position coordinates of root 'upper left corner' 
x = 0 
y = 0 

# make the root window the size of the image 
root.geometry("%dx%d+%d+%d" % (w, h, x, y)) 

# root has no image argument, so use a label as a panel 
panel1 = tk.Label(root, image=image1) 
panel1.pack(side='top', fill='both', expand='yes') 

# put a button on the image panel to test it 
button2 = tk.Button(panel1, text='button2') 
button2.pack(side='top') 

# save the panel's image from 'garbage collection' 
panel1.image = image1 

# start the event loop 
root.mainloop() 

當然,如果你比較熟悉的另一GUI,繼續和適應的例子,它不應該花費太多。

+0

非常感謝!這似乎很有前途! – MacPython 2010-07-02 15:55:06

4

你首先必須找到所有的圖像文件名。您可以使用os.listdir(...)獲取某個目錄中的所有文件,或使用​​查找與某個特定模式匹配的所有文件。

顯示圖像是第二個也是更具挑戰性的部分。第一種選擇是在外部程序中打開圖像,這可以是網絡瀏覽器。在(大多數)平臺上,命令firefox 1.jpeg將在Firefox瀏覽器中打開圖像1.jpeg。您可以使用subprocess模塊來執行這些命令。如果你想用一個漂亮的GUI來展示它們,你必須使用一些框架來創建一個GUI並使用它。但是如果你是初學者,這對你來說可能有點太難。

例如:

import glob 
import subprocess 
files = glob.glob('dir/*.jpeg') 
for file in files: 
    subprocess.call(['firefox', file]) 
+0

太棒了!非常感謝!我確實希望最終通過我自己的GUI或Django顯示它們。但我需要了解如何編寫python代碼來做到這一點,這非常有幫助! 謝謝 – MacPython 2010-07-02 14:09:39

0

這可能是一個更容易產生只是用圖片比對構建顯示圖片的GUI的靜態網頁。 您可以生成一個hmtl頁面,將圖像放在它上面,並用新創建的html文件啓動您的web瀏覽器。這給你一些佈局的可能性。

如果你只是想在瀏覽器中的圖片,然後muksie給了一個工作的例子。

+0

對不起,我需要使用Django,因爲這需要與Python集成。 – MacPython 2010-07-02 15:36:10

1

muksie的回答已經包含非常有用的建議。如果你不想自己寫HTML文件或者想要一些更漂亮的東西,你可以使用我爲MDP庫編寫的小腳本。這基本上允許你只是這樣做:

import slideshow 
slideshow.show_image_slideshow(filenames, image_size=(80,60)) 

這將創建一個HTML幻燈片,並在瀏覽器中打開它。你可以抓取所需的文件here(只需要templet.py和兩個slideshow文件),這可能比獲得完整的庫更好。

+0

謝謝!也非常好!我會檢查的!我最終想要實現的是一個網站,圖像依次顯示,每個圖像下面都會有一個按鈕。而更高級的選項將在一個網站上有多個圖像,這些圖像是可點擊的,如果點擊它們,則會點擊其他圖像。 – MacPython 2010-07-02 15:35:36