2017-01-22 223 views
1

我需要在背景(樓層地圖)圖像上繪製一個在畫布上移動的球。 我成功加載圖像,並繪製球移動,但畫布球不放在背景上。如何創建tkinter背景圖片?

import Tkinter as tk 
import random 
import time 
from PIL import ImageTk, Image 

root = tk.Tk() 
root.resizable(width=False, height=False) 
root.wm_attributes("-topmost", 1) 
path = 'C:\xx\Pictures\xxx.jpg' 
img = Image.open(path) 
photo = ImageTk.PhotoImage(img) 

class Ball: 
    def __init__(self, canvas, color): 
     self.canvas = canvas 
     self.id = canvas.create_oval(10, 10, 25, 25, fill=color) 
     self.canvas.move(self.id, 245, 100) 

    def draw(self): 
     self.canvas.move(self.id, 1, 1) 
     self.canvas.after(50, self.draw) 


canvas = tk.Canvas(root, bd=0, highlightthickness=0) 
canvas.pack() 
background_label = tk.Label(root, image = photo) 
background_label.place(x=0, y=0, relwidth=1.0, relheight=1.0, anchor="center") 
background_label.pack() 

ball = Ball(canvas, "red") 
ball.draw() #Changed per Bryan Oakley's comment. 
root.mainloop() 

回答

3

你在,將其放置下面畫布繪製的球,你必須在相同帆布加載圖像標籤加載圖像。

替換此

background_label = tk.Label(root, image = photo) 
background_label.place(x=0, y=0, relwidth=1.0, relheight=1.0, anchor="center") 
background_label.pack() 

與此:

canvas.create_image(0, 0, image=photo) 

確保創建映像創建之前將球得到z排序的權利。