How do I position a button to a canvas, not to the screen using Tkinter 3
Question:
I have a canvas with an image I’d like to use for a background. My problem is that when I position the button to the correct place, and I try to scroll down, the button moves with the screen instead of staying where I want it to on the canvas.
frame = Frame(self)
frame.pack()
mapImg = PhotoImage(file='Fo4-pip-map.png')
canvas = Canvas(frame, width=2048, height=2048, scrollregion=(0,0,2048,2048))
canvas.create_image(0,0, image=mapImg, anchor='nw')
canvas.image = mapImg
xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X, anchor='s')
yscrollbar = Scrollbar(frame, orient=VERTICAL)
yscrollbar.pack(side=RIGHT, fill=Y, anchor='e')
xscrollbar.config(command=canvas.xview)
yscrollbar.config(command=canvas.yview)
canvas.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
canvas.pack(side=LEFT, expand=True, fill=BOTH)
vaultImg = PhotoImage(file='Vault.png')
vaultImg = vaultImg.zoom(5)
vaultImg = vaultImg.subsample(32)
vault111Button = Button(canvas, width=30, height=30, borderwidth=0, image=vaultImg,
command=lambda: controller.show_frame('Vault111'))
vault111Button.image = vaultImg
vault111Button.place(x=150, y=100)
Answers:
The place
geometry manager places children at a fixed offset from their parent – in particular, the scrolling of a canvas doesn’t apply to them. Get rid of that last line, and instead use:
canvas.create_window(150, 100, window=vault111Button)
I have a canvas with an image I’d like to use for a background. My problem is that when I position the button to the correct place, and I try to scroll down, the button moves with the screen instead of staying where I want it to on the canvas.
frame = Frame(self)
frame.pack()
mapImg = PhotoImage(file='Fo4-pip-map.png')
canvas = Canvas(frame, width=2048, height=2048, scrollregion=(0,0,2048,2048))
canvas.create_image(0,0, image=mapImg, anchor='nw')
canvas.image = mapImg
xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X, anchor='s')
yscrollbar = Scrollbar(frame, orient=VERTICAL)
yscrollbar.pack(side=RIGHT, fill=Y, anchor='e')
xscrollbar.config(command=canvas.xview)
yscrollbar.config(command=canvas.yview)
canvas.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
canvas.pack(side=LEFT, expand=True, fill=BOTH)
vaultImg = PhotoImage(file='Vault.png')
vaultImg = vaultImg.zoom(5)
vaultImg = vaultImg.subsample(32)
vault111Button = Button(canvas, width=30, height=30, borderwidth=0, image=vaultImg,
command=lambda: controller.show_frame('Vault111'))
vault111Button.image = vaultImg
vault111Button.place(x=150, y=100)
The place
geometry manager places children at a fixed offset from their parent – in particular, the scrolling of a canvas doesn’t apply to them. Get rid of that last line, and instead use:
canvas.create_window(150, 100, window=vault111Button)