Identify button when generated in a for loop





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list, and the generation of the button and everything works. The only issue I have is that I don't know how to determine which button in my grid is clicked. My goal is to be able to click on a button and through that I know the coordinates of that in my grid [row][col].



This is the code I have so far.



from tkinter import *
from functools import partial
from itertools import product

# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):


# Define settings upon initialization. Here you can specify
def __init__(self, master=None):

# parameters that you want to send through the Frame class.
Frame.__init__(self, master)

#reference to the master widget, which is the tk window
self.master = master

#with that, we want to then run init_window, which doesn't yet exist
numRows = int(input("# of Rows: "))
numCols = int(input("# of Cols: "))

self.init_window(numRows, numCols)

#Creation of init_window
def init_window(self, rowNum, colNum):
# print(x, y)
# changing the title of our master widget
self.master.title("GUI")

# allowing the widget to take the full space of the root window
self.pack(fill=BOTH, expand=1)

# creating a button instance
#quitButton = Button(self, text="Exit",command=self.client_exit)

# placing the button on my window
#quitButton.place(x=0, y=0)
but =
for row in range(0, rowNum):
curRow =
for col in range(0, colNum):
curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))
curRow[col].grid(row=row,column=col)
but.append(curRow)

#but[1][1].config(state="disabled")
#but[1][1]["text"] = "3"
#but[1][1]["bg"] = "white"

def open_button(self, r, c):
print(r, " : ", c)

# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()

root.geometry("600x600")

#creation of an instance
app = Window(root)

#mainloop
root.mainloop()


Whenever I click on the grid, it gives me the very last button...
For example, a 9x9 grid always gives me "9 : 9" whenever I click any button.



Solutions welcomed! I want an easy way to get the coordinates without changing too much of the code (if possible).



Thanks!










share|improve this question































    1















    I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list, and the generation of the button and everything works. The only issue I have is that I don't know how to determine which button in my grid is clicked. My goal is to be able to click on a button and through that I know the coordinates of that in my grid [row][col].



    This is the code I have so far.



    from tkinter import *
    from functools import partial
    from itertools import product

    # Here, we are creating our class, Window, and inheriting from the Frame
    # class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
    class Window(Frame):


    # Define settings upon initialization. Here you can specify
    def __init__(self, master=None):

    # parameters that you want to send through the Frame class.
    Frame.__init__(self, master)

    #reference to the master widget, which is the tk window
    self.master = master

    #with that, we want to then run init_window, which doesn't yet exist
    numRows = int(input("# of Rows: "))
    numCols = int(input("# of Cols: "))

    self.init_window(numRows, numCols)

    #Creation of init_window
    def init_window(self, rowNum, colNum):
    # print(x, y)
    # changing the title of our master widget
    self.master.title("GUI")

    # allowing the widget to take the full space of the root window
    self.pack(fill=BOTH, expand=1)

    # creating a button instance
    #quitButton = Button(self, text="Exit",command=self.client_exit)

    # placing the button on my window
    #quitButton.place(x=0, y=0)
    but =
    for row in range(0, rowNum):
    curRow =
    for col in range(0, colNum):
    curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))
    curRow[col].grid(row=row,column=col)
    but.append(curRow)

    #but[1][1].config(state="disabled")
    #but[1][1]["text"] = "3"
    #but[1][1]["bg"] = "white"

    def open_button(self, r, c):
    print(r, " : ", c)

    # root window created. Here, that would be the only window, but
    # you can later have windows within windows.
    root = Tk()

    root.geometry("600x600")

    #creation of an instance
    app = Window(root)

    #mainloop
    root.mainloop()


    Whenever I click on the grid, it gives me the very last button...
    For example, a 9x9 grid always gives me "9 : 9" whenever I click any button.



    Solutions welcomed! I want an easy way to get the coordinates without changing too much of the code (if possible).



    Thanks!










    share|improve this question



























      1












      1








      1


      0






      I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list, and the generation of the button and everything works. The only issue I have is that I don't know how to determine which button in my grid is clicked. My goal is to be able to click on a button and through that I know the coordinates of that in my grid [row][col].



      This is the code I have so far.



      from tkinter import *
      from functools import partial
      from itertools import product

      # Here, we are creating our class, Window, and inheriting from the Frame
      # class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
      class Window(Frame):


      # Define settings upon initialization. Here you can specify
      def __init__(self, master=None):

      # parameters that you want to send through the Frame class.
      Frame.__init__(self, master)

      #reference to the master widget, which is the tk window
      self.master = master

      #with that, we want to then run init_window, which doesn't yet exist
      numRows = int(input("# of Rows: "))
      numCols = int(input("# of Cols: "))

      self.init_window(numRows, numCols)

      #Creation of init_window
      def init_window(self, rowNum, colNum):
      # print(x, y)
      # changing the title of our master widget
      self.master.title("GUI")

      # allowing the widget to take the full space of the root window
      self.pack(fill=BOTH, expand=1)

      # creating a button instance
      #quitButton = Button(self, text="Exit",command=self.client_exit)

      # placing the button on my window
      #quitButton.place(x=0, y=0)
      but =
      for row in range(0, rowNum):
      curRow =
      for col in range(0, colNum):
      curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))
      curRow[col].grid(row=row,column=col)
      but.append(curRow)

      #but[1][1].config(state="disabled")
      #but[1][1]["text"] = "3"
      #but[1][1]["bg"] = "white"

      def open_button(self, r, c):
      print(r, " : ", c)

      # root window created. Here, that would be the only window, but
      # you can later have windows within windows.
      root = Tk()

      root.geometry("600x600")

      #creation of an instance
      app = Window(root)

      #mainloop
      root.mainloop()


      Whenever I click on the grid, it gives me the very last button...
      For example, a 9x9 grid always gives me "9 : 9" whenever I click any button.



      Solutions welcomed! I want an easy way to get the coordinates without changing too much of the code (if possible).



      Thanks!










      share|improve this question
















      I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list, and the generation of the button and everything works. The only issue I have is that I don't know how to determine which button in my grid is clicked. My goal is to be able to click on a button and through that I know the coordinates of that in my grid [row][col].



      This is the code I have so far.



      from tkinter import *
      from functools import partial
      from itertools import product

      # Here, we are creating our class, Window, and inheriting from the Frame
      # class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
      class Window(Frame):


      # Define settings upon initialization. Here you can specify
      def __init__(self, master=None):

      # parameters that you want to send through the Frame class.
      Frame.__init__(self, master)

      #reference to the master widget, which is the tk window
      self.master = master

      #with that, we want to then run init_window, which doesn't yet exist
      numRows = int(input("# of Rows: "))
      numCols = int(input("# of Cols: "))

      self.init_window(numRows, numCols)

      #Creation of init_window
      def init_window(self, rowNum, colNum):
      # print(x, y)
      # changing the title of our master widget
      self.master.title("GUI")

      # allowing the widget to take the full space of the root window
      self.pack(fill=BOTH, expand=1)

      # creating a button instance
      #quitButton = Button(self, text="Exit",command=self.client_exit)

      # placing the button on my window
      #quitButton.place(x=0, y=0)
      but =
      for row in range(0, rowNum):
      curRow =
      for col in range(0, colNum):
      curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))
      curRow[col].grid(row=row,column=col)
      but.append(curRow)

      #but[1][1].config(state="disabled")
      #but[1][1]["text"] = "3"
      #but[1][1]["bg"] = "white"

      def open_button(self, r, c):
      print(r, " : ", c)

      # root window created. Here, that would be the only window, but
      # you can later have windows within windows.
      root = Tk()

      root.geometry("600x600")

      #creation of an instance
      app = Window(root)

      #mainloop
      root.mainloop()


      Whenever I click on the grid, it gives me the very last button...
      For example, a 9x9 grid always gives me "9 : 9" whenever I click any button.



      Solutions welcomed! I want an easy way to get the coordinates without changing too much of the code (if possible).



      Thanks!







      python python-3.x button tkinter






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 '18 at 15:53









      Bryan Oakley

      223k22279440




      223k22279440










      asked Nov 17 '18 at 3:15









      Pranay AgrawalPranay Agrawal

      84




      84
























          1 Answer
          1






          active

          oldest

          votes


















          2














          The row and col variables are assigned each value in the ranges. At the end of the loop that generates the buttons, the values for those variables are left at the last values in the ranges, e.g. "9 : 9".



          Try replacing the line



          curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))


          with



          curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda rw=row, cl=col: self.open_button(rw, cl)))


          This assigns the values of row and col at the time the button is created to the variables rw and cl, which remain the same for each button as the for-loop iterates.



          See this link:
          Tkinter assign button command in loop with lambda






          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347864%2fidentify-button-when-generated-in-a-for-loop%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            The row and col variables are assigned each value in the ranges. At the end of the loop that generates the buttons, the values for those variables are left at the last values in the ranges, e.g. "9 : 9".



            Try replacing the line



            curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))


            with



            curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda rw=row, cl=col: self.open_button(rw, cl)))


            This assigns the values of row and col at the time the button is created to the variables rw and cl, which remain the same for each button as the for-loop iterates.



            See this link:
            Tkinter assign button command in loop with lambda






            share|improve this answer






























              2














              The row and col variables are assigned each value in the ranges. At the end of the loop that generates the buttons, the values for those variables are left at the last values in the ranges, e.g. "9 : 9".



              Try replacing the line



              curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))


              with



              curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda rw=row, cl=col: self.open_button(rw, cl)))


              This assigns the values of row and col at the time the button is created to the variables rw and cl, which remain the same for each button as the for-loop iterates.



              See this link:
              Tkinter assign button command in loop with lambda






              share|improve this answer




























                2












                2








                2







                The row and col variables are assigned each value in the ranges. At the end of the loop that generates the buttons, the values for those variables are left at the last values in the ranges, e.g. "9 : 9".



                Try replacing the line



                curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))


                with



                curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda rw=row, cl=col: self.open_button(rw, cl)))


                This assigns the values of row and col at the time the button is created to the variables rw and cl, which remain the same for each button as the for-loop iterates.



                See this link:
                Tkinter assign button command in loop with lambda






                share|improve this answer















                The row and col variables are assigned each value in the ranges. At the end of the loop that generates the buttons, the values for those variables are left at the last values in the ranges, e.g. "9 : 9".



                Try replacing the line



                curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda: self.open_button(row, col)))


                with



                curRow.append(Button(self, bg="gray", width=2,height=1, command=lambda rw=row, cl=col: self.open_button(rw, cl)))


                This assigns the values of row and col at the time the button is created to the variables rw and cl, which remain the same for each button as the for-loop iterates.



                See this link:
                Tkinter assign button command in loop with lambda







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 17 '18 at 4:09

























                answered Nov 17 '18 at 4:03









                eniviumenivium

                588




                588
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347864%2fidentify-button-when-generated-in-a-for-loop%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine