你能在不添加新的 canvas 元素的情况下设置 tkinter 背景图像吗?

Can you set a tkinter background image without adding a new canvas element?

我有一个 Python tkinter 程序简化为

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, height=200, width=200, bg="salmon")
canvas.pack(fill=tk.BOTH, expand=tk.YES)

def click(event):
    print(event.x)
    print(event.y)

def release(event):
    print(event.x)
    print(event.y)

canvas.bind("<Button-1>", click)
canvas.bind("<ButtonRelease-1>", release)

root.mainloop()

以 Canvas 作为主要元素。 Canvas 绑定了 click/release 个事件(例如 returning event.xevent.y)。我想以这种方式向 canvas 添加背景图片:

canvas = tk.Canvas(root, bg='/path/to/image.png')

我已经通过使用 canvas.create_image 方法在 canvas 上创建图像来设置背景图像,如 Adding a background image in python 中所述。但是,这破坏了我的程序,因为背景图像的 event.xevent.y return 位置。

我正在寻找一种解决方案,它会强制我更改最少的现有代码。

我们需要使用 PhotoImage 加载图像以供使用,然后我们使用 create_image 将该图像设置为 canvas。

试一试:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, height=200, width=200, bg="salmon")
canvas.pack(fill=tk.BOTH, expand=tk.YES)

def click(event):
    print(event.x)
    print(event.y)

def release(event):
    print(event.x)
    print(event.y)

canvas.bind("<Button-1>", click)
canvas.bind("<ButtonRelease-1>", release)

my_image = tk.PhotoImage(file='/path/to/image.png')
canvas.create_image(10, 10, image=my_image, anchor='nw')

root.mainloop()

在 canvas 上创建背景图像的唯一方法是在 canvas 上创建图像对象。这样做不会影响示例中绑定函数返回的坐标。