2

What I'm looking for is how to create a grid of buttons automatically with an iteration.

For example I have this array

Array = 
       [[0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0], 
        [0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0]]

And I look something like

from tkinter import *

window = Tk ()
def create_buttons ():
    global Array
    for rows in Array:
       for numbers in rows:
           button = Button (text = 'Hello')
           button.pack () 
window.mainloop ()

Any help will be appreciated

7
  • what problem are you having? Have you actually tried creating a button in your loop? Commented May 27, 2016 at 1:20
  • I'm starting to program with Python, so i don't have a lot of experience Commented May 27, 2016 at 1:52
  • It creates the buttons, but vertically and it doesn't let me use the grid I edited the algoritm in the question Commented May 27, 2016 at 1:54
  • have you tried searching this site for "create buttons in a loop"? there are lots of examples. Commented May 27, 2016 at 1:57
  • Yes, and they worked, but now the problem is that it doesn't let me arrange them in a grid, like the array Commented May 27, 2016 at 1:59

1 Answer 1

2

Let us put in an MCVE what @BryanOakley advised you to do using object-oriented concepts.

In below code, initialize() method creates a 6x7 numpy array of zeros (as yours), then loops over its 2 axes (dimensions) to create a button on each iteration:

'''
Created on May 27, 2016

@author: Billal BEGUERADJ
'''

import Tkinter as Tk
import numpy as np

class Begueradj(Tk.Frame):
   def __init__(self,parent):
      Tk.Frame.__init__(self, parent)
      self.parent = parent
      self.initialize()

   def initialize(self):
      '''
      Draw the GUI
      '''
      self.parent.title("RUN ON START TEST")       
      self.parent.grid_rowconfigure(1,weight=1)
      self.parent.grid_columnconfigure(1,weight=1)

      self.frame = Tk.Frame(self.parent)  
      self.frame.pack(fill=Tk.X, padx=5, pady=5)

      # Create a 6x7 array of zeros as the one you used
      self.a = np.zeros((6,7))
      for i in range(0,self.a.shape[0]):
          for j in range(0,self.a.shape[1]):
               self.b = Tk.Button(self.frame, text = 'Hello')
               self.b.grid(row=i,  column= j)

# Start the main program here               
if __name__ == "__main__": 
   root=Tk.Tk()
   app = Begueradj(root)   
   root.mainloop()

Here is what you get after running the above program:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.