我是一名入门级 Python 程序员,希望创建一款猜猜猜猜风格的游戏。在大学里,我还没有学会如何导入图像并将它们绑定(bind)到屏幕上的固定位置(类似于游戏板)。有什么方法可以单击特定图像并在选择特定字符(图像)的位置发生 onClickEvent。 我的大部分编码能力都在 python 中,但我怀疑这是否是执行此类项目的最佳语言。
请您参考如下方法:
每个 GUI 都有 Button 小部件,可以点击并且(大部分)可以显示图像。
但大多数情况下,在 GUI 中,您可以将点击事件分配给每个对象,即。 Label 和 Image。
即。 Tkinter
import tkinter as tk
from PIL import Image, ImageTk
# --- functions ---
def on_click(event=None):
# `command=` calls function without argument
# `bind` calls function with one argument
print("image clicked")
# --- main ---
# init
root = tk.Tk()
# load image
image = Image.open("image.png")
photo = ImageTk.PhotoImage(image)
# label with image
l = tk.Label(root, image=photo)
l.pack()
# bind click event to image
l.bind('<Button-1>', on_click)
# button with image binded to the same function
b = tk.Button(root, image=photo, command=on_click)
b.pack()
# button with text closing window
b = tk.Button(root, text="Close", command=root.destroy)
b.pack()
# "start the engine"
root.mainloop()
像 PyGame 这样的图形模块也可以显示图像,并且有点击事件,但有时你必须手动检查你是否点击了带有图像的区域(并且你必须创建 mainloop 手动)
