[Tutor] Shortening the code
Alan Gauld
alan.gauld at btinternet.com
Sat Nov 26 15:19:19 CET 2011
On 26/11/11 12:52, Mic wrote:
> Alright! By the way, it seems like some people favour the use of pastebins,
> while others don’t, which is the way to go and why?
I've stated my preference, Steven has stated his, so I guess you need to
decide for yourself. However the best bet is not to paste long pieces of
code at all, but stick to samples. They are easier to read and therefore
more likely to get a reply...
> Strange, I got that error now when I tried to run it just now. But it
> took like 30 seconds for the error to actually
> appear. Do you have any idea why this happened?
How are you running the code?
From a command prompt or inside an IDE?
> Yes it works perfectly fine now. I wonder, in the last section of the code:
> >button.grid(row=row, column=column)
> Could I put columnspan in there?
> Like:
> Button.grid(row=row, column=column, columnspan=columnspan)
Yes, its an option to grid()
use The Python help system(I'm on 2.7)
>>> help(Tkinter.Button.grid)
yields:
Help on method grid_configure in module Tkinter:
grid_configure(self, cnf={}, **kw) unbound Tkinter.Button method
Position a widget in the parent widget in a grid. Use as options:
column=number - use cell identified with given column (starting
with 0)
columnspan=number - this widget will span several columns
in=master - use master to contain this widget
in_=master - see 'in' option description
ipadx=amount - add internal padding in x direction
ipady=amount - add internal padding in y direction
padx=amount - add padding in x direction
pady=amount - add padding in y direction
row=number - use cell identified with given row (starting with 0)
rowspan=number - this widget will span several rows
sticky=NSEW - if cell is larger on which sides will this
widget stick to the cell boundary
And then just try it out...
> earlier on, would I somehow put them in the list, list_chair?
Yes, its just another value. You could use a default like 0 or -1 where
you don't want a span. Then in your code test before calling grid:
for row, col, span, name in chairs_list:
.....
if span == 0:
button.grid(row=row,column=col)
else:
button.grid(row=row,column=col,columnspan=span)
> Assuming you feel that it is time for do this, how do I implement the
> creation of these text files into the code that we discussed earlier?
The easiest way is just to use regular Python data structures in a
separate python file. Then you just import that file. So using your
chair_list, you would put that in a sepasrate file like:
list_chair = [
#row, col, span, name
(0, 1, 0, '01'),
(0, 2, 0, '02'),
(0, 3, 0, '03'),
(0, 4, 0, '04'),
(1, 1, 2, '05'),
(1, 3, 2, '06')
]
Assume you call it chair_config.py
You can then import the data with
from chair_config import list_chair
And the rest of your code remains the same.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list