【问题标题】:Display multiple images on background tkinter and PIL?在背景 tkinter 和 PIL 上显示多个图像?
【发布时间】:2024-04-13 21:15:02
【问题描述】:

我尝试使用 tkinter 构建一个 gui,以将文字放在地图上,用于英雄联盟等游戏。 使用 tkinter 创建这样一个 gui 的速度令人惊讶,但我遇到了一个我似乎无法单独解决的问题:

点击事件的功能(在画布/地图上创建文字图片):

def sightstone(event):
 i = Image.open('Sightstone_item.png')
 i = i.resize((10, 10), Image.ANTIALIAS)
 img = ImageTk.PhotoImage(i)
 sword = tk.Label(panel, image=img, compound=tk.CENTER)
 sword.place(x=event.x, y=event.y, width=10, height=10)
 sword.image = img
 n = len(words) + 1
 string = 'sword '
 words.update({string + '%d' % n: [(event.x, event.y)]})
 dump.update({string + '%d' % n: [sword, img, i]})
 print('clicked at', event.x, event.y)

休息一下:

window = tk.Tk()
Canvas = tk.Canvas(window, width=768, height=810)
img = Image.open('srift.jpg')
img = img.resize((768, 810), Image.ANTIALIAS)
mapimg = ImageTk.PhotoImage(img)
panel = tk.Label(window, image=mapimg)
panel.bind("<Control-Button-1>", sightstone)
panel.place(x=0, y=0, relwidth=1, relheight=1)
i = Image.open('Sightstone_item.png')
i = i.resize((10, 10), Image.ANTIALIAS)
img = ImageTk.PhotoImage(i)
sword1 = tk.Label(panel, image=img, compound=tk.CENTER)
sword1.place(x=384, y=405, width=10, height=10)
sword1.image = img
sword2 = tk.Label(panel, image=img, compound=tk.CENTER)
sword2.place(x=405, y=405, width=10, height=10)
sword2.image = img
Canvas.pack()
words = {}; dump = {}; string = ''
Canvas.find_all()
window.mainloop()

请注意,我创建剑 1 和剑 2 只是为了展示我想要的样子。但是如果我ctrl+左键点击创建另一个wordsword1和2就消失了。获取 event.x 和 event.y 或单词的坐标非常重要,因为我想用它做一些事情。

【问题讨论】:

    标签: python image tkinter python-imaging-library


    【解决方案1】:

    感谢回答的 joaquin here! 我改变的是:我创建了一个 Canvas 并在画布上创建了背景图像,而不是生成标签。

    #in sightstone(event) change following:
    sward = tk.Label(Canvas, image=img, compound=tk.CENTER)
    #then in main:
    Canvas.create_image(384, 405, image=mapimg)
    Canvas.bind("<Control-Button-1>", sightstone)
    Canvas.pack(expand = 'yes', fill = 'both')
    

    现在一切正常。 =^)

    【讨论】: