2014-03-05 133 views
1

嗨,我想把圖像作爲我的按鈕之一的背景,我已經在我的主窗口中的很多其他按鈕上做了這個,但這個特定的按鈕坐在頂級窗口內,圖像不會像它應該加載,有沒有人知道爲什麼? (我也曾嘗試定義按鈕的寬度和高度,但仍然不顯示圖像)tkinter按鈕不顯示圖像

def rec_window(): 
    recw = Toplevel(width=500,height=500) 
    recw.title('Record To.....') 
    img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif") 
    Button(recw, image=img1, command=rec_preset_1).grid(row=1, column=1) 
    Button(recw, text="Preset 2", bg = 'grey70',width=40, height=12,command=rec_preset_2).grid(row=1, column=2) 
    Button(recw, text="Preset 3", bg = 'grey70',width=40, height=12,command=rec_preset_3).grid(row=2, column=1) 
    Button(recw, text="Preset 4", bg = 'grey70',width=40, height=12,command=rec_preset_4).grid(row=2, column=2) 
    Button(recw, text="Cancel", bg='grey70', width=20, height=6, command=recw.destroy). grid(row=3,column=1,columnspan=2, pady=30) 

回答

2

根據如何你的程序的其他部分的結構,你的形象可能會得到通過garbage-清除收藏:

http://effbot.org/tkinterbook/photoimage.htm

注:當一個光象對象被垃圾收集的Python(如 當你從存儲在本地 可變圖像的功能返回),圖像被清除即使它S是由 Tkinter的插件顯示。

爲了避免這種情況,程序必須保留對圖像 對象的額外引用。一個簡單的方法來做到這一點是將圖像分配給控件 屬性,像這樣:

label = Label(image=photo) 
label.image = photo # keep a reference! 
label.pack() 

在你的情況,你可以通過聲明IMG1作爲一個全局變量保持基準啓動功能:

global img1 

或者,如果你已經有IMG1在程序的其它地方:

img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif") 
img1Btn = Button(recw, image=img1, command=rec_preset_1) 
img1Btn.image = img1 
img1Btn.grid(row=1, column=1) 
+0

有這個(這裏)沒有(http://www.tkdocs.com /tutorial/widgets.html)或[這裏](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Button.html),這正是爲什麼一個圖標沒有出現在我的應用程序中的一個按鈕 - 非常感謝。 –