首页 > 解决方案 > Tkinter / Python 循环索引问题

问题描述

我正在尝试使用带有 Python 3 的 Tkinter 制作一个基本的井字游戏。

在 add_buttons 方法中,我将按钮添加到第 i 行第 j 列。但是,当我调用 add_move 方法时,i 和 j 值始终显示为 2,2。这意味着在我的二维数组“buttonGrid”中,只有最后一个列表中的最后一个元素从 None 变为 x。

为什么会发生这种情况,我该怎么做才能将其他位置值传递给“add_move”方法?(另外,对于任何糟糕的编码习惯,我们深表歉意!)

from functools import partial

class Window(Frame):
    def __init__(self, master = None): # init Window class
        Frame.__init__(self, master) # init Frame class
        self.master = master # allows us to refer to root as master
        self.rows = 3
        self.columns = 3
        self.buttonGrid = [[None for x in range(self.rows)] for y in range(self.columns)]

        self.create_window()
        self.add_buttons()

    def create_window(self):

        #title
        self.master.title('Tic Tac Toe')

        self.pack(fill = BOTH, expand = 1)
        for i in range(0,3): # allows buttons to expand to frame size
            self.grid_columnconfigure(i, weight = 1)
            self.grid_rowconfigure(i, weight = 1)


    def add_buttons(self):
        rows = 3
        columns = 3
        # create a 2d array to put each button in
        # Creates a list containing 3 lists, each of 3 items, all set to None

        for i in range (rows):
            for j in range(columns):
                button_ij = Button(self, textvariable = self.buttonGrid[i][j], command = lambda: self.add_move(i,j))
                # sticky centres buttons and removes space between adjacent buttons
                button_ij.grid(row = i,column = j, sticky =E+W+S+N)

    def add_move(self, i,j): # only 2 and 2 passed in as i and j
        self.buttonGrid[i][j] = 'X'
        print(i,j)
        print(self.buttonGrid)



root = Tk() # creating Tk instance

rootWidth = '500'
rootHeight = '500'
root.geometry(rootWidth+'x'+rootHeight)

ticTacToe = Window(root) # creating Window object with root as master

root.mainloop() # keeps program running

标签: python-3.xloopstkinterindexing

解决方案


推荐阅读