【发布时间】: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, "<Button-1>", nav())有问题。该函数需要作为参数本身 ->nav而不是使用nav()调用它。Button也应该是button。 -
这样吗?
my_canvas.tag_bind(button, "<Button-1>", nav)将代码更新到此,但它仍然无法正常工作,当我单击图像时没有任何反应,终端中没有打印任何内容,也没有显示错误。
标签: python python-3.x tkinter