0

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.

Jan
  • 144
  • 1
  • 11
  • If you give us a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) of this code we can provide the proper feedback to your question. – Mike - SMT Jul 25 '17 at 18:02
  • @SierraMountainTech I have edited my question providing very simplified code. – Jan Jul 25 '17 at 18:16
  • 1
    You are trying to add an image as a background color with this line: `canvas = tk.Canvas(root, bg='/path/to/image.png')` – Mike - SMT Jul 25 '17 at 18:21
  • @SierraMountainTech no, I know this is not possible. I would like my background image to act like a background colour (not interfering with my bind events). – Jan Jul 25 '17 at 18:26
  • Take a look at the code I posted. It will not interfere with your bindings. I tested it on my end and it worked fine. – Mike - SMT Jul 25 '17 at 18:27

2 Answers2

1

The only way to create a background image on a canvas is to create an image object on the canvas. Doing so will not affect the coordinates returned by the bound functions in your example.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0

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()
Mike - SMT
  • 14,784
  • 4
  • 35
  • 79