在tkinter python中单击鼠标左键捕获棋子位置并在右键单击时更改其位置

时间:2018-09-20 15:03:25

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

您好,我最近开始学习tkinter并决定参加棋盘游戏。
下面是我的代码:

import tkinter as tk

class GameBoard(tk.Frame):
def __init__(self, parent, rows=8, columns=8, size=70, color1="white", color2="blue"):
    '''size is the size of a square, in pixels'''

    self.rows = rows
    self.columns = columns
    self.size = size
    self.color1 = color1
    self.color2 = color2
    self.pieces = {}

    canvas_width = columns * size
    canvas_height = rows * size

    tk.Frame.__init__(self, parent)
    self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
                            width=canvas_width, height=canvas_height, background="bisque")
    self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)
    self.canvas.bind("<Button-1>", self.capture_piece)

root = tk.Tk()
board = GameBoard(root)
board.pack(side="top", fill="both", expand="true", padx=4, pady=4)

black_rook_l = tk.PhotoImage(file=black_rook_img)
black_rook_l = black_rook_l.subsample(2, 2)
board.addpiece("black_rook_l", black_rook_l, 0,0)

以上代码i是将一块(黑鸦)添加到板上,该板可以按预期工作。 下面是辅助函数:

def capture_piece(self, event):
    print(event)
    # pass

def addpiece(self, name, image, row=0, column=0):
    '''Add a piece to the playing board'''
    self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c")
    self.placepiece(name, row, column)
    self.images.append(image)

def placepiece(self, name, row, column):
    '''Place a piece at the given row/column'''
    self.pieces[name] = (row, column)
    x0 = (column * self.size) + int(self.size/2)
    y0 = (row * self.size) + int(self.size/2)
    # print(name, x0, y0)
    self.canvas.coords(name, x0, y0)

函数capture_piece正在打印
ButtonPress事件状态= Mod1 num = 1 x = 42 y = 100
我也不知道状态和数字是什么,我想要块,行和列的名称,以便知道块的位置(行,列),然后单击鼠标右键,我可以获取目标位置并将其放置/ image到新位置。
很抱歉,如果我错过了一些事情。
请提出建议/帮助。
预先感谢。

0 个答案:

没有答案