Drawing a grid

From Scribus Wiki
Jump to navigation Jump to search
This article is part of the Scripts series.

Using Tcl/TK to define the Grid

This script accomplishes a relatively simple task – making a grid structure on the document. Aside from requiring a document to be open, it requires Tkinter, a Python module for creating Tk structures, such as the dialog you see to the right.

Grid.png

The resulting grid is formed from a series of horizontal and vertical lines – this is important to know, since if you plan to move the grid after creation you will want to group the lines.

Limitations

The default values for the grid suggest it was created with millimeters in mind, since most other page units would probably make use of a different set. Like all the scripts in Scribus, you could make your own version and change these parameters, but the dialog of course allows this as well. You must use integer values for this dialog (in other words, whole numbers, no decimals), otherwise it hangs until you correctly enter integers. You cannot adjust the thickness or color of the lines without altering the script, but these could be accomplished in Scribus afterward.

Drawgrid1.png
To the left you can see also that you are responsible for making sure the X-step and Y-step are appropriate for the overall size of your grid if you want a border on all four sides.
# -*- coding: utf-8 -*-

"""
DESCRIPTION & USAGE:
This script needs Tkinter. It will create a GUI with available options
for easy grid creation. You'll geta grid a the specified position.
The units are the same as you documents.

Steps to create:
    1) Fill requested values in the Grid dialog

AUTHOR:
    Rüdiger Härtel <r_haertel [at] gmx [dot] de>

LICENSE:
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""

import sys

try:
    import scribus
except ImportError,err:
    print 'This Python script is written for the Scribus scripting interface.'
    print 'It can only be run from within Scribus.'
    sys.exit(1)

try:
    # I wish PyQt installed everywhere :-/
    from Tkinter import *
    from tkFont import Font
except ImportError:
    print "This script requires Python's Tkinter properly installed."
    messageBox('Script failed',
               'This script requires Python\'s Tkinter properly installed.',
               ICON_CRITICAL)
    sys.exit(1)


def grid(x,y,width,height,xstep,ystep,color):
    """ """
    xend = x + width
    yend = y + height
    
    for _x in range(x,xend+1,xstep):
         line = scribus.createLine(_x,y,_x,yend)
         scribus.setLineColor(color, line)
    
    for _y in range(y,yend+1,ystep):
         line = scribus.createLine(x,_y,xend,_y)
         scribus.setLineColor(color, line)


class TkGrid(Frame):
    """ GUI interface for Scribus calendar wizard.
        It's ugly and very simple. I can say I hate Tkinter :-/"""
    
    def __init__(self, master=None):
        """ Setup the dialog """
        # reference to the localization dictionary
        self.key = 'default'
        Frame.__init__(self, master)
        self.grid()
        self.master.title('Scribus Grid Wizard')
        
        #define variables
        self.x = IntVar()
        self.y = IntVar()
        
        self.w = IntVar()
        self.h = IntVar()
        
        self.xs = IntVar()
        self.ys = IntVar()
        
        # default values
        self.x.set(15)
        self.y.set(15)
        self.w.set(100)
        self.h.set(100)
        self.xs.set(5)
        self.ys.set(5)
        
        #define widgets
        self.xLabel = Label(self, text='x-Pos')
        self.yLabel = Label(self, text='y-Pos')
        
        self.wLabel = Label(self, text='Width')
        self.hLabel = Label(self, text='Height')
        
        self.xsLabel = Label(self, text='x-Step')
        self.ysLabel = Label(self, text='y-Step')
        
        self.xEntry = Entry(self, textvariable=self.x, width=4)
        self.yEntry = Entry(self, textvariable=self.y, width=4)
        
        self.wEntry = Entry(self, textvariable=self.w, width=4)
        self.hEntry = Entry(self, textvariable=self.h, width=4)
        
        self.xsEntry = Entry(self, textvariable=self.xs, width=4)
        self.ysEntry = Entry(self, textvariable=self.ys, width=4)
        
        self.okButton = Button(self, text="   OK   ", width=6, command=self.okButon_pressed)
        self.cancelButton = Button(self, text="Cancel", command=self.quit)
        
        self.xLabel.grid(column=0,row=0,padx=5,pady=5)
        self.xEntry.grid(column=1,row=0)
        
        self.yLabel.grid(column=0,row=1,padx=5,pady=5)
        self.yEntry.grid(column=1,row=1)
        
        self.wLabel.grid(column=2,row=0,padx=5,pady=5)
        self.wEntry.grid(column=3,row=0)
        self.hLabel.grid(column=2,row=1,padx=5,pady=5)
        self.hEntry.grid(column=3,row=1)
        
        self.xsLabel.grid(column=0,row=2,padx=5,pady=5)
        self.xsEntry.grid(column=1,row=2)
        self.ysLabel.grid(column=0,row=3,padx=5,pady=5)
        self.ysEntry.grid(column=1,row=3,padx=5)
        
        self.okButton.grid(column=0,columnspan=2,row=4)
        self.cancelButton.grid(column=2,columnspan=2,row=4,padx=5,pady=5)

    def okButon_pressed(self):
        grid(self.x.get(),self.y.get(),self.w.get(),self.h.get(),self.xs.get(),self.ys.get(),"Black")
        self.quit()

    def quit(self):
        self.master.destroy()

def main():
    """ Application/Dialog loop with Scribus sauce around """
    if scribus.haveDoc() == 0:
	scribus.messageBox("Error", "Please create a Document", ICON_WARNING, BUTTON_OK)
	return
    
    try:
        scribus.statusMessage('Running script...')
        scribus.progressReset()
        root = Tk()
        app = TkGrid(root)
        root.mainloop()
    finally:
        if scribus.haveDoc():
            scribus.redrawAll()
        scribus.statusMessage('Done.')
        scribus.progressReset()

if __name__ == '__main__':
    main()


Creating a grid based on the shape currently selected

This script will work for Scribus 1.3.7 upwards.


"""
this script creates a grid based on the rectangular shape currently selected
@author: alessandro rimoldi
@version: 1.0 / 20090131
@copyright (c) 2009 alessandro rimoldi under the mit license
           http://www.opensource.org/licenses/mit-license.html
"""
import sys
try:
   import scribus
except ImportError:
   print "This script only works from within Scribus"
   sys.exit(1)

# check that the selection is one text frame and get that frame
frame_n = scribus.selectionCount()
if frame_n == 0 :
    scribus.messageBox('Error:', 'No frame selected');
    sys.exit(1)
elif frame_n > 1 :
    scribus.messageBox('Error:', 'You may select only one frame');
    sys.exit(1)

frame = scribus.getSelectedObject(0)
objectType = scribus.getObjectType();
#scribus.messageBox('Info:', objectType);
if (objectType != 'Polygon') :
    scribus.messageBox('Error:', 'You have to first create a shape of the size of the grid');

w, h = scribus.getSize(frame)
# scribus.messageBox('Message:', 'w'+str(w)+'h'+str(h));
x, y = scribus.getPosition(frame)
string = scribus.valueDialog('Define the grid', 'How many columns and rows? (c,r)', '10,10');
# scribus.messageBox('Message:', string);
c, string, r = string.partition(',');
# scribus.messageBox('Message:', 'c'+c+'r'+r);
c = int(c);
r = int(r);
dx = w/c;
dy = h/r;
l = list();
for i in range (0, c + 1) :
  a = x + (i * dx);
  line = scribus.createLine(a, y, a, y+h);
  l.append(line);
for i in range (0, r + 1) :
  a = y + (i * dy);
  line = scribus.createLine(x, a, x+w, a);
  l.append(line);

scribus.groupObjects(l);

scribus.deleteObject(frame);

sys.exit(1)