gpt4 book ai didi

python - Python 的可点击图像

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:52 25 4
gpt4 key购买 nike

我是一名入门级 Python 程序员,希望创建一款猜猜猜猜风格的游戏。在大学里,我还没有学会如何导入图像并将它们绑定(bind)到屏幕上的固定位置(类似于游戏板)。有什么方法可以单击特定图像并在选择特定字符(图像)的位置发生 onClickEvent。我的大部分编码能力都在 python 中,但我怀疑这是否是执行此类项目的最佳语言。

最佳答案

每个 GUI 都有 Button 小部件,可以点击并且(大部分)可以显示图像。

但大多数情况下,在 GUI 中,您可以将点击事件分配给每个对象,即。 LabelImage

即。 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 手动)

关于python - Python 的可点击图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com