首页 > 解决方案 > 如何在 Python 的 Tkinter 中使用 .create_image

问题描述

我正在尝试制作一个简单的游戏,您可以在其中单击按钮并在屏幕上显示饮料的图像,如何使用 .create_image 在我喜欢的位置显示图像?我知道relx/rely不完全有效,所以最好的解决方案是什么

canvas.create_image() 中传递的参数到底是什么?

from tkinter import *
from tkinter import messagebox
from PIL import Image

window = Tk()
window.geometry('1500x800')
window.resizable(1, 1)
window.config()
window.title('Bar simulator')

bg = PhotoImage(file='C:/Python/bar game/bar2.png')
bg_label = Label(window, image=bg)
bg_label.place(relwidth=1, relheight=1)

canvas = Canvas()
# canvas.pack()
# canvas.create_image(anchor='n', image=bg)

beer = PhotoImage(file='C:/Python/bar game/beer.png')
# beer_img = canvas.create_image(30, 13, image=beer)

# canvas.create_image(30, 30, image=beer)

title = Label(window, text='Welcome to the Bar!', bg='brown', font=('arial 30 bold'))
title.place(relx=0.345)
subtitle = Label(window, text='What would you like to drink?', bg='brown', font='arial 20 bold')
subtitle.place(relx=0.35, rely=0.1)

def alcohol():
    msg = messagebox.askquestion('Age warning', 'Are you over 18?')
    if msg == 'yes':
        messagebox.showinfo('Age warning', 'enjoy your drink!')
        return canvas.create_image(300, 13, anchor=NW, image=beer)
    else:
        messagebox.showinfo('Age warning', 'You are to old to drink!')


beer_button = Button(window, text='Beer', cursor='hand2', bg='yellow', command=alcohol, bd=5, width=10, fg='orange', font='arial 15 bold')
beer_button.place(relx=0.1, rely=0.2)
wine_button = Button(window, text='Wine', cursor='hand2', bg='#C70039', command=alcohol, bd=5, width=10, fg='white', font='arial 15 bold')
wine_button.place(relx=0.3, rely=0.2)
vodka_button = Button(window, text='Vodka', cursor='hand2', bg='blue', command=alcohol, bd=5, width=10, fg='white', font='arial 15 bold')
vodka_button.place(relx=0.5, rely=0.2)
sake_button = Button(window, text='Sake', cursor='hand2', bg='white', command=alcohol, bd=6, width=10, fg='blue', font='arial 15 bold')
sake_button.place(relx=0.7, rely=0.2)

window.mainloop()

标签: pythontkintercanvas

解决方案


无论如何,您可以简单地阅读文档来创建图像,您可以使用:

img = PhotoImage(file='image.png') #transparent image
canvas.create_image(x,y,image=img,anchor='ne') 

这将基于 -anchor 选项在 (x,y) 坐标处创建图像。还有更多选项,例如 -state、-tags、-disabledimage。阅读文档。这是我在这里能找到的唯一问题。还注意到您没有将任何坐标传递到:

canvas.create_image(anchor='n', image=bg)

推荐阅读