pythontkintertkinter-canvas

python tkinter cannot implement lift method on canvas


I am trying to lift and lower a canvas object in Python Tkinter. I tried canvas.lower() but it's resulting in an error prompting

_tkinter.TclError:wrong # args: should be ".!canvas lower tag0rld "belowThis?

my script:

import tkinter as tk
import PIL.ImageTk as itk
window=tk.Tk()
image1=itk.PhotoImage(file="image_1.png")
canvas1 = tk.Canvas(window)
a=canvas1.create_image(0,0,image=image1)
canvas1.place(x=100,y=100)
canvas1.lower()
image2 = itk.PhotoImage(file="image_2.png")
canvas2 = tk.Canvas(window)
b = canvas2.create_image(0,0,image=image2)
canvas2.place(x=100,y=130)
window.mainloop()

the images are just a black square and a white square, so they shouldn't matter.


Solution

  • Lowering the whole canvas:

    import tkinter as tk
    
    import tkinter as tk
    
    window = tk.Tk()
    canvas1 = tk.Canvas(window, bg="red")
    canvas1.place(x=100,y=100)
    
    canvas2 = tk.Canvas(window, bg="blue")
    canvas2.place(x=100,y=130)
    
    canvas2.tk.call('lower', canvas2._w, None)
    
    window.mainloop()
    
    root.mainloop()
    

    This directly calls the tcl command but still works. The problem was that in the definition of tkinter.Canvas:

    class Canvas(Widget, XView, YView):
        ...
        def tag_lower(self, *args):
            """Lower an item TAGORID given in ARGS
            (optional below another item)."""
            self.tk.call((self._w, 'lower') + args)
        lower = tag_lower
    

    It overrides the Misc class's (the base class for all widgets) method .lower that lowers the widget. So I directly called what the Misc class would have called: self.tk.call('lower', self._w, belowThis)