2016-11-07 70 views
1

我一個月前開始學習Python。對不起,如果我的問題不好,這是我的第一個問題。如何將標籤背景更改爲相同的圖片

我已經使用tkinter做了一個小遊戲,但我遇到了問題。

我製作了一張大圖片作爲背景。每當我製作更多帶有文字的標籤時,文字都會有灰色背景。但是我想要的是每個文本都有我已經作爲背景放置的圖片。

下面是一些代碼來解釋它:

from tkinter import* 
x=Tk() 
x.geometry("1000x1000") 
z=PhotoImage(file="D:\\Blue.gif") 
v=Label(x,text="hi",font=100,fg="red",compound=CENTER,image=z,width=1000,height=1000) 
v.place(x=0,y=0) 
v1=Label(x,text="OO",font=100,fg="red") 
v1.place(x=300,y=400) 
x.mainloop() 

v標籤的作品非常好,只要我使用的化合物與它。它顯示帶有文字「嗨」的圖片。 但是,我希望v1標籤具有與v相同的背景,而不是灰色背景。

+0

所有小部件都有背景。你可以使用[Canvas](http://effbot.org/tkinterbook/canvas.htm)來放置圖片和文字。 – furas

回答

0

所有小部件都有背景 - 它們不能透明。

您可以使用tk.Canvas將沒有背景的文字放在圖像上或文字上的透明圖像上。

effbot.org:CanvasPhotoImage

#!/usr/bin/env python3 

import tkinter as tk 
from PIL import Image, ImageTk 

# --- constants --- 

WIDTH = 800 
HEIGHT = 600 

# --- main --- 

root = tk.Tk() 

c = tk.Canvas(root, width=WIDTH, height=HEIGHT) 
c.pack() 

# only GIF and PGM/PPM 
#photo = tk.PhotoImage(file='test.gif') 

# other formats 
image = Image.open('test_transparent.png') 
photo = ImageTk.PhotoImage(image) 
# use in functions - solution for "garbage collector" problem 
c.image = photo 

i = c.create_image((WIDTH//2, HEIGHT//2), image=photo) 
t = c.create_text((WIDTH//2, HEIGHT//2), text='Hello World') 

root.mainloop() 

修改訂單,你會得到圖像上的文字

t = c.create_text((WIDTH//2, HEIGHT//2), text='Hello World') 
i = c.create_image((WIDTH//2, HEIGHT//2), image=photo) 

test_transparent.png(與透明背景圖片)

enter image description here