【问题标题】:How to create a tkinter background image?如何创建 tkinter 背景图像?
【发布时间】:2017-01-22 18:20:59
【问题描述】:

我需要用背景(平面图)图像绘制一个在画布上移动的球。 我成功加载了图像,并绘制了移动的球,但画布球没有放在背景的顶部。

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()

【问题讨论】:

    标签: python canvas tkinter


    【解决方案1】:

    您将图像加载到放置在您绘制球的画布中的标签中。您必须将图像加载到相同的画布中。

    替换这个

    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 顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 2011-03-13
      • 1970-01-01
      相关资源
      最近更新 更多