2013-05-01 53 views
1

我是Python和Tkinter的初學者。我試圖在左上角放置一張圖片,但是我不能。我嘗試了財產「證明」和「錨」。這是我的代碼:在Tkinter中加載角落中的圖像

logo_upb = PhotoImage(file="upb.gif") 
label = Label(root, image=logo_upb, justify=LEFT) 
label.image = logo_upb 
label.place(bordermode=INSIDE, x=0, y=0) 
label.pack() 

我會感謝任何解決方案。

回答

3

您是否嘗試過網格幾何管理器。

網格幾何管理器將窗口小部件放入二維表中。你會驚訝地發現使用網格管理器而不是打包器會更容易。

讓我們用這個例子來展示網格可以做什麼。使用包管理器創建此佈局是可能的,但需要多個額外的框架小部件。

tkinter grid example

但隨着網格幾何管理器,你也可以有小部件跨越多個小區。 columnspan選項用於讓一個窗口小部件跨越多個列< checkbutton>和<圖像>,而rowspan選項可讓它跨越多行<圖像>。

下面的代碼創建的顯示佈局:

label1.grid(sticky=E) 
label2.grid(sticky=E) 

entry1.grid(row=0, column=1) 
entry2.grid(row=1, column=1) 

checkbutton.grid(columnspan=2, sticky=W) 

image.grid(row=0, column=2, columnspan=2, rowspan=2, 
      sticky=W+E+N+S, padx=5, pady=5) 

button1.grid(row=2, column=2) 
button2.grid(row=2, column=3) 

所以,你的答案會是相同的<標籤1>換句話說格的位置將是row = 0,並column = 1。 Tkinter對GIF有本地支持,所以不需要額外的庫。

import Tkinter as tk 

root = tk.Tk() 
img = tk.PhotoImage(file ="somefile.gif") 
panel = tk.Label(root, image = img) 
panel.grid(row=0,column=1) 
root.mainloop() 

我個人的建議是使用Python圖像庫(PIL)鏈接:http://www.pythonware.com/products/pil/增加更多支持的文件格式的遊戲。支持的文件格式列表:http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html

在這個例子中,我使用了在tkinter中本地不支持的.jpg文件格式,並且所有工作都很完美,因爲我們使用的是PIL。

import Tkinter as tk 
from PIL import ImageTk,Image 

root = tk.Tk() 
img = ImageTk.PhotoImage(Image.open("somefile.jpg")) 
panel = tk.Label(root, image = img) 
panel.grid(row=0,column=1) 
root.mainloop() 

警告:請勿混合電網,並在同一個主窗口包。 Tkinter會很樂意度過餘生,試圖談判一個解決方案,兩位經理都很滿意。而不是等待,殺死應用程序,再看看你的代碼。一個常見的錯誤是對一些小部件使用錯誤的父項。

LINK:http://effbot.org/tkinterbook/grid.htm

+0

在你的例子中,如果你所顯示的只是一個GIF,你不需要PIL,tkinter對GIF有本地支持。否則,優秀的答案! – 2013-05-01 11:25:57

+0

Personaly我一直使用PIL(這是一個很棒的庫),所以例如可以有「somefile.jpg」或「somefile.png」等,並且在支持的文件格式的定義分辨率時,所有這些都可以很好地工作。 ](http://infohost.nmt.edu/tcc/help/pubs/pil/formats。HTML)我會編輯我的答案,以更好地理解這個例子... – 2013-05-01 13:19:22

0

有關問題的具體原因是,您使用的地方更多或更少正確,則拋出所有位置遠,當你調用pack()place,packgrid不是免費的 - 您只能使用一個來管理任何特定的小部件。

+0

thx爲您的答案。我明白我的錯誤。 – 2013-05-01 14:12:56