【问题标题】:python3 tkinter GUI with clickable transparent imagespython3 tkinter GUI,带有可点击的透明图像
【发布时间】:2022-01-16 10:36:24
【问题描述】:

我在 inkscape 中为我的 GUI 制作了背景,并设法在顶部添加了一个透明图像以用作按钮,但无法弄清楚如何让它们在单击时运行子例程 (nav)。我要么需要一个在我的背景顶部具有透明度的图像,我可以单击它,要么需要一个完全透视的矩形,我可以将它定位在在 inkscape 的背景图像上绘制的按钮上。如果重要的话,我在 Ubuntu 上。

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()

【问题讨论】:

  • my_canvas.tag_bind(Button, "&lt;Button-1&gt;", nav()) 有问题。该函数需要作为参数本身 -> nav 而不是使用 nav() 调用它。 Button 也应该是 button
  • 这样吗? my_canvas.tag_bind(button, "&lt;Button-1&gt;", nav) 将代码更新到此,但它仍然无法正常工作,当我单击图像时没有任何反应,终端中没有打印任何内容,也没有显示错误。

标签: python python-3.x tkinter


【解决方案1】:

当使用my_canvas.tag_bind(button, "&lt;Button-1&gt;", nav) 调用函数时,nav(root) 实际上是在单击时被调用的,因此必须使用def nav(root): 才能使子例程正确运行。

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    相关资源
    最近更新 更多