简体   繁体   中英

python3 tkinter GUI with clickable transparent images

I have made a background for my GUI in inkscape and have managed to add a transparent image over the top to use as buttons but cant figure out how to make them run a subroutine (nav) when clicked. I either need an image with transparency over the top of my background that I can click or a completely see through rectangle that I can position over a button drawn on the background image in inkscape. I'm on Ubuntu if it matters.

from tkinter import *
from PIL import ImageTk, Image
import sys

root = Tk ()

root.title('GUI')

root.geometry("1000x564")
root.attributes('-zoomed', True)
root.attributes("-type", "splash")
#define image
bg = ImageTk.PhotoImage(file="BACKGROUND.png")

#create canvas
my_canvas = Canvas(root, width=800, height=500)
my_canvas.pack(fill="both", expand=True)
my_canvas.create_image(0,0, image=bg, anchor = NW)

def nav():
  print ("navigation")
  
#creating button which supports png transparency
#button = PhotoImage(file="button2.png")
#my_canvas.create_image(260,-70, anchor=NW, image=button, state='normal', )

buttonImage = ImageTk.PhotoImage(Image.open("button.png"))
button = my_canvas.create_image(50, 50, image=buttonImage)
my_canvas.tag_bind(Button, "<Button-1>", nav())



def resizer(e):
  global bg1, resized_bg, new_bg

  # open image
  bg1 = Image.open("BACKGROUND.png")
  # resize
  resized_bg =bg1.resize((e.width, e.height), Image.ANTIALIAS)

  #DEFINE IMAGE AGAIN
  new_bg =ImageTk.PhotoImage(resized_bg)

  #add back to the canvas
  my_canvas.create_image(0,0, image=new_bg, anchor = NW)
 # my_canvas.create_image(260,-70, anchor=NW, image=button, state='normal', )
  button = my_canvas.create_image(50, 50, image=buttonImage)

  
def close(e):
 root.destroy()

  
root.bind('<Configure>', resizer)


root.bind('<Escape>', close)


root.mainloop()

when calling function with my_canvas.tag_bind(button, "<Button-1>", nav) nav(root) is actually being called when clicked so def nav(root): has to be used for the sub routine to run correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM