Jan Jan - 3 years ago 111
Python Question

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

I have a Python tkinter program simplified to

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


with a Canvas as the main element. Canvas has click/release events bound to it (e.g. returning
event.x
and
event.y
). I want to add a background image to the canvas in this manner:

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


I have managed to set a background image by creating an image on the canvas using
canvas.create_image
method, as explained in Adding a background image in python. However, this broke my program as
event.x
and
event.y
return position of the background image.

I am looking for a solution that would force me to change the least of the existing code.

Answer Source

We need to use PhotoImage to load the image for use then we use create_image to set that image to the canvas.

Give this a shot:

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download