Assign return-value to unnamed, clicked button

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jogi
    New Member
    • Mar 2010
    • 6

    Assign return-value to unnamed, clicked button

    How can I assign a value that is returned from a function to an unnamed button that just called the function?

    Code:
    def felder_updaten(m):
    	for i in range(9):
    		for j in range(9):
    			Button(mainframe, text=m[i][j], command=insert_number).grid(row=i, column=j, sticky=W+E)
    m is a 9x9 matrix (btw, it's a Sudoku-solver).
    Or, if it can't be done that way, how can I dynamically name 81 buttons (like btn1, btn2, btn3...btn81)

    Thanks a lot!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    What do you mean, "assign a value that is returned from a function to an unnamed button that just called the function"? Do you mean that you want to replace the text in the button? Create a handler for the buttons and attach an event binding to each button with widget method bind(). It's easier than it sounds.
    Code:
    import Tkinter
    import random
    """Start with a grid of buttons with blank labels. When a button is
    clicked, change the text to a random number between 1 and 100."""
    
    textFont3 = ("Arial", 12, "bold")
    
    class App(Tkinter.Tk):
        def __init__(self, cols, rows):
            Tkinter.Tk.__init__(self)
            self.title("Grid of Buttons")
            self.cols = cols
            self.rows = rows
            
            self.mainFrame = Tkinter.Frame(self)
            self.mainFrame.grid()
            self.create_buttons()
    
        def create_buttons(self):
            for i in range(self.cols):
                for j in range(self.rows):
                    btn = Tkinter.Button(self.mainFrame,text="", width=4)
                    btn.grid(row=j, column=i)
                    btn.bind(sequence="<ButtonRelease-1>", func=self.handler)
    
        def handler(self, event):
            event.widget.configure(text=random.randint(1,100))
    
    app = App(6,6)
    app.mainloop()

    Comment

    • Jogi
      New Member
      • Mar 2010
      • 6

      #3
      That's it - nearly.
      Is it possible to give additional parameters to the func=self.handl er ? (in addition to 'event')... i tried 'func=self.hand ler(matrix,i,j) ', but then the event is missing.

      Or if not, is it possible to give the (new) text of the button as parameter, so that the new number can be inserted into the matrix?

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Most definitely! It is a bit more complicated. You can create a different handler for each button making use of default arguments. Example:
        Code:
        import Tkinter
        import random
        """Start with a grid of buttons with blank labels. When clicked, change the
        text to a random number between 1 and 100."""
        
        textFont3 = ("Arial", 12, "bold")
        
        class App(Tkinter.Tk):
            def __init__(self, cols, rows):
                Tkinter.Tk.__init__(self)
                self.title("Grid of Buttons")
                self.cols = cols
                self.rows = rows
                
                self.mainFrame = Tkinter.Frame(self)
                self.mainFrame.config(padx='3.0m', pady='3.0m')
                self.mainFrame.grid()
                # initialize button array
                self.buttonList = [[None for j in range(cols)] for i in range(rows)]
                self.create_buttons()
        
            def create_buttons(self):
                for i in range(self.cols):
                    for j in range(self.rows):
                        btn = Tkinter.Button(self.mainFrame,text="",
                                         anchor='center',
                                         bd=3,
                                         bg='#ffffff000',
                                         fg="#000000fff",
                                         activebackground = "#000000fff",
                                         activeforeground = "#ffffff000",
                                         font=textFont3,
                                         padx='1.0m',
                                         pady='1.0m',
                                         relief='raised',
                                         state='normal', width=6)
                        self.buttonList[i].append(btn)
        
                        btn.grid(row=j, column=i)
                        def handler(event, i=i, j=j):
                            return self.__buttonHandler(event, i, j)
                        btn.bind(sequence="<ButtonRelease-1>", func=handler)
        
            def __buttonHandler(self, event, i, j):
                event.widget.configure(text=", ".join([str(obj) for obj in [i, j, random.randint(1,100)]]))
        
        app = App(6,6)
        app.mainloop()

        Comment

        • Jogi
          New Member
          • Mar 2010
          • 6

          #5
          Ok, i think that might work :D
          Thank you!

          Comment

          Working...