如何将图像移动限制在其所在的帧内?

问题描述 投票:0回答:1

我有一个程序,如果您单击图像而不是单击您想要移动的方块,则可以移动图像。我有两个帧,都具有相同的图像,但我想将图像移动限制为仅它们当前所在的帧。

我尝试过做

if self.squares[0, dict_rank_pieces or self.white_images] in self.squares[1, pos]
之类的事情,但这不起作用

class Board(tk.Frame):

    def __init__(self, parent, length, width):  # self=Frame, parent=root

        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.length = length
        self.width = width
        self.config(height=100 * self.length, width=100 * self.width)
        self.frame1 = tk.Frame(self)
        self.frame2 = tk.Frame(self)
        self.pack()

        self.square_color = None
        self.squares = {}
        self.ranks = string.ascii_lowercase
        self.white_images = {}  # stores images of pieces
        self.black_images = {}
        self.white_pieces = ["image1", "image2", "image3", "image4", "image5"]
        self.black_pieces = ["image1", "image2", "image3", "image4", "image5"]
        self.buttons_pressed = 0
        self.turns = 0
        self.sq1 = None  # first square clicked
        self.sq2 = None
        self.sq1_button = None  # button associated with the square clicked
        self.sq2_button = None
        self.piece_color = None
        self.set_squares()

    def select_piece(self, button):
        if self.buttons_pressed == 0:
            self.sq1 = list(self.squares.keys())[list(self.squares.values()).index(button)]
            self.sq1_button = button
            self.buttons_pressed += 1

        elif self.buttons_pressed == 1:  # stores square and button of second square selected
            self.sq2 = list(self.squares.keys())[list(self.squares.values()).index(button)]
            self.sq2_button = button
            if self.sq2 == self.sq1:
                self.buttons_pressed = 0
                return
            if True:
                self.squares[self.sq2].config(image=self.sq1_button["image"])
                self.squares[self.sq2].image = self.sq1_button["image"]
                self.squares[self.sq1].config(image=self.white_images["blank.png"])  # clears sq1
                self.squares[self.sq1].image = self.white_images["blank.png"]
                self.buttons_pressed = 0
                return

    def set_squares(self):  # fills frame with buttons representing squares

        for x in range(5):
            for y in range(5):
                for i, frame in enumerate((self.frame1, self.frame2)):
                    pos = self.ranks[x] + str(y + 1)
                    b = tk.Button(frame, bg=self.square_color, activebackground="lawn green")
                    b.grid(row=x, column=y, sticky="nsew")
                    b.config(command=lambda key=b: self.select_piece(key))
                    self.squares[i, pos] = b
    

    def import_pieces(self):  # opens and stores images of pieces and prepares the pieces for the game for both sides
        path = os.path.join(os.path.dirname(__file__), "white")  # stores white pieces images into dicts
        w_dirs = os.listdir(path)
        for file in w_dirs:
            img = Image.open(path + "/" + file)
            img = img.resize((80, 80), Image.Resampling.LANCZOS)
            img = ImageTk.PhotoImage(image=img)
            self.white_images.setdefault(file, img)

    def set_pieces(self):  # places pieces in starting positions
        dict_rank_pieces = {"a": "dirt.png", "b": "fire.png", "c": "metal.png", "d": "water.png", "e": "wood.png"}
        blank_piece = "blank.png"
        for rank in range(1, 6):  # fill rest with blank pieces
            for file in range(5):
                starting_piece = dict_rank_pieces[self.ranks[file]]
                pos = self.ranks[file] + str(rank)
                self.squares[0, pos].config(image=self.white_images[starting_piece if rank == 1 else blank_piece])
                self.squares[1, pos].config(image=self.white_images[starting_piece if rank == 5 else blank_piece])

        self.frame1.pack(side='left')
        self.frame2.pack(side='right')


root = tk.Tk()
root.geometry("800x800")
board = Board(root, 5, 5)
board.import_pieces()
board.set_pieces()
board.mainloop()
python dictionary tkinter frames
1个回答
0
投票

正如我在其他问题的评论中所说,您可以使用self.squares

key
,即
self.sq1
self.sq2
的值,其格式为(frame_index,position),来确定所选方块是否在同一框中:

def select_piece(self, button):
    if self.buttons_pressed == 0:
        ...
    elif self.buttons_pressed == 1:
        ...
        # do nothing if same square is selected
        # or they are not in same frame
        if (self.sq2 == self.sq1) or (self.sq2[0] != self.sq1[0]):
            self.button_pressed = 0
            return
        ...
© www.soinside.com 2019 - 2024. All rights reserved.