Anonymous Coder
Anonymous Coder

Reputation: 542

Is there any way to display an image over a button in tkinter canvas?

Is there any way to display an image in a tkinter canvas so that it appears over a button created in that same tkinter canvas? My code looks something like this:

from tkinter import *

root = Tk()

canvas = Canvas(root, bg="red")
button = Button(canvas, text="Example")
image = PhotoImage(file="image")

canvas.pack()
button.grid(row=0, column=0)
canvas.create_image(0, 0, image=image)

root.mainloop()

However, this only shows the button and not the image. How can I resolve this?

Note: The solution must use modules that come default with Python (so no PIL) as this program needs to be used in an environment where I cannot download other modules.

Upvotes: 0

Views: 880

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

You can add an image as part of the button (with the image and compound options). You can also use place to place a label with an image over a button. Another option is to create a label with an image as a canvas item, as long as it is higher in the stacking order than the button.

What you can't do, however, is create canvas objects that overlap widgets, as widgets always have the highest stacking order on a canvas.

This is what the canonical tk documentation says:

The items in a canvas are ordered for purposes of display, with the first item in the display list being displayed first, followed by the next item in the list, and so on. Items later in the display list obscure those that are earlier in the display list and are sometimes referred to as being “on top” of earlier items. When a new item is created it is placed at the end of the display list, on top of everything else. Widget commands may be used to re-arrange the order of the display list.

Window items are an exception to the above rules. The underlying window systems require them always to be drawn on top of other items. In addition, the stacking order of window items is not affected by any of the canvas widget commands; you must use the raise and lower Tk commands instead.

Upvotes: 1

Related Questions