Reputation: 2312
I have massively reduced the amount of repetitive code by using a loop in Python to create, format and store Pmw EntryFields in my project rather than build individual widgets. I even managed to place them in a linear fashion on the root window -- one under the other in column 0.
However, when I want to place them in two columns I cannot find a way to generate the following widget row and column coordinates
(0,0)(0 1),(1,0)(1,1)(2,0)(2,1) from the for loop. I used a workaround which was to type the above coordinates into a Python list and refer to the list.
import tkinter
import Pmw
import time
root=tkinter.Tk() #Create a main GUI window
root.option_readfile('optionDB') #Override Windows default fonts
##root.resizable(width=False, height=False) #Fix the window size in stone
root.iconbitmap('logo.ico') #add logo
titles=['a', 'b','c', 'd','e','f'] #List ttitles of entry fields
**locations=[(0,0),(0,1),(1,0),(1,1),(2,0),(2,1)]** #Entry locations
entry ={} #Container for referencing entry fieleds
for nextWidget in range(len(titles)): #Buils widgets on the page
dummy_x= Pmw.EntryField(root, #widget properties
labelpos = 'w',
label_text = titles[nextWidget],
label_fg="white",
entry_width=10
)
Pmw.Color.changecolor(dummy_x.component("hull"),
background="blue")
**dummy_x.grid(row= locations[nextWidget][0],**
column=locations[nextWidget][1],
padx=10,pady=10
)
entry.update({titles[nextWidget]: dummy_x}) #add to container
root.mainloop() #run the venet loop
You can see in the main for loop I iterate over the list called locations and placing the values in the row, column attributes of the grid() option to place the widgets.
Question: To eliminate the locations list altogether is there a way to generate the sequence (0,0)(0 1),(1,0)(1,1)(2,0)(2,1) from the for loop iteself?
Upvotes: 1
Views: 425
Reputation:
The general answer for all cases is you can use a for()
for this_row in range(3):
for this_column in range(2):
print this_row, this_column
or increment counters
this_row=0
this_column=0
for nextWidget in range(len(titles)):
...
this_column += 1
if this_column > 1:
this_row += 1
this_column = 0
or test for nextWidget%2 = similar to above but divmod works better than modulus for this
for ctr in range(6):
print divmod(ctr, 2)
Upvotes: 1
Reputation: 386010
(i/2, i%2)
(python2), or (i//2, i%2)
(python3) will will give you the numbers you want, if you only need two columns
$ python3 -i
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> for i in range(10):
... print((i//2, i%2))
...
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
(3, 0)
(3, 1)
(4, 0)
(4, 1)
>>>
Upvotes: 1