【问题标题】:How do I use the .create_image in Tkinter in Python如何在 Python 的 Tkinter 中使用 .create_image
【发布时间】:2020-12-14 14:40:32
【问题描述】:

我正在尝试制作一个简单的游戏,您可以在其中单击按钮并在屏幕上显示饮料的图像, 如何使用 .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()

【问题讨论】:

  • tkdoc。顺便说一句,为什么不使用标签呢?
  • 我的图片是透明的,但是 label 方法为图片设置了默认的白色背景

标签: python tkinter canvas


【解决方案1】:

你可以简单地阅读文档,无论如何,要创建一个图像,你会使用:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2021-03-03
    • 2018-09-24
    • 2021-05-19
    • 2018-11-29
    相关资源
    最近更新 更多