python - 如何在 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()
解决方案
无论如何,您可以简单地阅读文档来创建图像,您可以使用:
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)
推荐阅读
- linux - 配置:错误:*** POSIX caps headers not found when building SystemCtl on CentOS
- flutter - google_maps_flutter - 无法调整自定义图标的大小
- excel - 为 Combobox 的唯一值源创建字典 - 添加另一个列源
- flutter - Flutter 如何在 dart 中使用 json decode 将字符串转换为列表
- html - 在导航栏中放置搜索栏
- facebook - 我的 facebook messenger 聊天插件未显示在我的网站地址上
- javascript - 成功验证验证码的事件侦听器
- r - 如何解决 ModuleNotFoundError:R 中没有名为“stanfordnlp”的模块
- c++ - 为什么 maxHeap 初始化语法通过 priority_queue 与 minHeap 不同?
- javascript - Any way to get my discord token from Browser Dev Console?