2017-06-02 848 views
0

我已經研究出瞭如何爲按鈕設置圖像,即定位在標籤頂部(我想我可能會這樣做,因爲我無法安裝PIL我的Mac出於某種原因)。無論如何,它在某種程度上應該起作用 - 我遇到的問題是它會在任何一方添加空白區域,然後圖像本身不會顯示其透明背景。Tkinter - 按鈕圖像透明背景

enter image description here

我使用的代碼如下:

from tkinter import * 
#from PIL import Image 

root = Tk() 


#Removes the title bar and places over mac top bar 
root.tk.call("::tk::unsupported::MacWindowStyle", "style", root._w, "plain", "none") 
# Makes the app full screen 
#root.wm_attributes('-fullscreen', 1) 

root.geometry('{}x{}'.format(480, 320)) 
#root.attributes('-topmost', True) 

def quitApp(): 
    # mlabel = Label (root, text = 'Close').pack() 
    root.destroy() 


background_img = PhotoImage(file="images/bg.gif") 
scanBtn_img = PhotoImage(file="images/scanBtn.gif") 

background = Label(root, 
        compound = CENTER, 
        quitButton = Button(image=scanBtn_img, command = quitApp).pack(), 
        image = background_img).pack(side="right") 

background.image = background_img # keep a reference! 


root.mainloop() 
+0

你確定你在Python 2.7,因爲你導入tkinter小寫爲python 3. –

回答

0

從我瞭解的Tkinter本身支持像GIF圖像的透明度。

我把你的代碼切碎了一點,但它確實對我有用。也許在設置代碼方面存在問題。您的標籤中還有一個按鈕。我不認爲你需要兩者都有。你可以在你想要的地方創建按鈕。

僅供參考,我在黑色背景的不同側面上創建了一個標籤和一個按鈕,以顯示圖像的透明度。

這是我用來測試gif的代碼我有透明度。爲了以防萬一,我在python 3.6和2.7上測試了這個。

from tkinter import * 

root = Tk() 

def quitApp(): 
    root.destroy() 

background_img = PhotoImage(file="Colors/sa.gif") 
scanBtn_img = PhotoImage(file="Colors/sa.gif") 

background = Label(root,bg='black', image = background_img).pack(side = RIGHT)    
quitButton = Button(bg='black', image=scanBtn_img, command = quitApp).pack(side = LEFT) 
backgroundimage = background_img # keep a reference! 

root.mainloop() 

更新:我用您的評論

鏈接GIF下面是結果。

enter image description here

更新:

後做一些更多的挖我找到了可能用於Mac OS工作:

我沒有一臺Mac,現在來測試,所以讓我知道如果這適用於你:

from tkinter import * 

root = Tk() 

# Hide the root window drag bar and close button 
root.overrideredirect(True) 
# Make the root window always on top 
root.wm_attributes("-topmost", True) 
# Make the window content area transparent 
root.wm_attributes("-transparent", True) 
# Set the root window background color to a transparent color 
root.config(bg='systemTransparent') 

def quitApp(): 
    root.destroy() 

background_img = PhotoImage(file="Colors/1.gif") 
scanBtn_img = PhotoImage(file="Colors/1.gif") 

background = Label(root,bg='black', image = background_img).pack(side = RIGHT) 
background.config(bg='systemTransparent') 
quitButton = Button(bg='black', image=scanBtn_img, command = quitApp).pack(side = LEFT) 
quitButton.config(bg='systemTransparent') 
backgroundimage = background_img # keep a reference! 

root.mainloop() 
+0

嗨,它看起來像這個f或我http://prntscr.com/ff5sm7 – BCLtd

+0

這必須是一個mac的東西。我將不得不多看看它。 –

+0

啊可以解釋一下,我正在使用這個圖片https://image.prntscr.com/image/d036fce797e94291bd38040bd7eb4bd0.gif – BCLtd