【问题标题】:How to detect click on image?如何检测点击图片?
【发布时间】:2018-02-24 21:03:06
【问题描述】:

伙计们,我目前正在使用 Tkinter 在 Python 中制作国际象棋,想知道如何检测图像是否被点击?

此代码为我存储在字典中的每个图像添加了一个点击功能

def MouseClickOnEachPiece(self, rows, columns, event): 

   global AllPieces

   while True:
     for ThePieces in AllPieces:
         if board[rows][columns] == ThePieces:
             self.canvas.bind('<Button-1>', MakeMove)
         elif board[rows][columns] != ThePieces:
             continue 

此代码用于移动

def MakeMove(self, rows, columns, event):

    global AllPieces

    print("You have clicked at: ", event.x , event.y)

    while True:
        for i in AllPieces:
            if #the image is clicked : # -- What would i use to check if the image is clicked?
                canvas.move(i, #themove )

【问题讨论】:

  • 对于棋盘来说,您所要做的就是检查点击位置吗?一个简单的计算应该可以告诉你确切的棋盘位置。
  • 画布有一个 bind 方法来绑定到画布上的单个项目。这个方法有文档记录,本站有很多关于画布对象绑定的问答。

标签: python python-3.x tkinter tkinter-canvas


【解决方案1】:

如果可能,您可以使用按钮并在按钮上放置图像。

from tkinter import *
from tkinter import ttk

root = Tk()

button = ttk.Button(root)
button.pack()

theImage = PhotoImage(file = "source")

button.config(image = theImage)

【讨论】:

  • 如果我在按钮上使用 .move 功能,按钮能否随图片一起移动?
  • 完成此操作后,您的图像具有透明部分,它会显示为白色,而不是背景颜色。我有任何方法可以使按钮透明,所以你能看到的只是图像
猜你喜欢
  • 2014-01-26
  • 2011-12-07
  • 2015-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
相关资源
最近更新 更多