Matt
Matt

Reputation: 1

Placing image over an image with buttons

I currently have a canvas with a background image and buttons on top of it. I am trying to get it so that when a certain button is clicked, a new image will be laid over the top of the background image and buttons. What I have right now is this:

import tkinter as tk
from xlrd import *
from PIL import Image, ImageTk

#GLOBAL VARIABLES

WIDTH = 720
HEIGHT = 960

#create window
window = tk.Tk()
window.title("NFL")
window.geometry("960x720")

#create canvas
canvas = tk.Canvas(window, width = WIDTH*2, height = HEIGHT*2)
canvas.pack()

#use NFL logo as background
nfl_logo_image = Image.open('nfl.jpg')
nfl_logo_image = nfl_logo_image.resize((HEIGHT, WIDTH), Image.ANTIALIAS)
nfl_logo = ImageTk.PhotoImage(nfl_logo_image)
canvas.create_image(0, 0, image = nfl_logo, anchor = 'nw')

#CAR button
def press_car_button():
    canvas2 = tk.Canvas(window, width = WIDTH*2, height = HEIGHT*2)
    canvas2.pack()
    big_car_logo = Image.open('car.png')
    big_car_logo = big_car_logo.resize((WIDTH, WIDTH), Image.ANTIALIAS)
    big_car_image = ImageTk.PhotoImage(big_car_logo)
    canvas2.create_image(0, 0, image = big_car_image, anchor = 'nw')

car_logo = Image.open('car.png')
car_logo = car_logo.resize((70,70), Image.ANTIALIAS)
car_image = ImageTk.PhotoImage(car_logo)
car_button = tk.Button(window, image = car_image, height = 70, width = 70, command = press_car_button)
car_button_window = canvas.create_window(720, 195, anchor = 'nw', window = car_button)

#run GUI
window.mainloop()

When I run this, the background image and button both come up fine, but when I click on the button, nothing happens.

Thanks in advance for any help!

Upvotes: 0

Views: 329

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

You are forcing the window to be a specific size. Then, you use pack without any options which means the new canvas is packed to the top of the available space. That means that it's packed below the other canvas, which means it won't be visible since the first canvas is twice the window height.

There are many solutions, all dependent on exactly what you want to happen. For one, instead of creating a new canvas you can simply re-use the existing canvas by adding a new image. Or, you can use a new canvas after first hiding the old with place_forget. Or, you can use grid or place to insure that both canvases are put on the window at the same location.

Upvotes: 1

Related Questions