cress
cress

Reputation: 409

Vertical align string in Tkinter Radiobutton with specified width

I need help aligning a string in a Tkinter Radiobutton

Window

As you can see, it is not perfectly aligned. How can I get the "Goal" text to be vertically aligned? I am doing it like this:

pairs = [None for x in range(10)]
for i in range(len(startList)):
  pairs[i] = (''.join(["Start: (", str(startList[i].X), ",", str(startList[i]), ")", '{:>20}'.format(''.join(["Goal: (", str(goalList[i].X), ",", str(goalList[i].Y), ")"]))]), i)

radioRow = Frame(self)
radioRow.pack(fill=Y)
v = IntVar()
v.set(0)

for text, mode in pairs:
    rdButton = Radiobutton(radioRow, text=text, variable=v, value=mode)
rdButton.pack(anchor=W)

Upvotes: 1

Views: 1886

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386230

Separate the text into two widgets: a radiobutton and a label. Then make the parent of the radiobuttons and labels a frame, and use grid to arrange them in a two column by ten row matrix.

Here's a rough example:

import Tkinter as tk

data = (
    ((111,2), (14,90)),
    ((46, 1), (16, 111)),
    ((94, 1), (16, 111)),
)

root = tk.Tk()
choices = tk.Frame(root, borderwidth=2, relief="groove")
choices.pack(side="top", fill="both", expand=True, padx=10, pady=10)

v = tk.StringVar()
for row, (start, goal) in enumerate(data):
    button = tk.Radiobutton(choices, text="Start (%s,%s)" % start, value=start, variable=v)
    label = tk.Label(choices, text="Goal: (%s, %s)" % goal)
    button.grid(row=row, column=0, sticky="w")
    label.grid(row=row, column=1, sticky="w")

# give the invisible row below the last row a weight, so any
# extra space is given to it
choices.grid_rowconfigure(row+1, weight=1)

root.mainloop()

Upvotes: 2

furas
furas

Reputation: 142824

You have to align Start, not Goal - {:<10} - so it will use always 10 chars. And then Goal will start in the same place. But it will work ideally only with monospaced fonts

data = [
    (111, 2, 14, 90),
    (46, 1, 16, 111),
    (94, 1, 38, 1),
]

for a, b, c, d in data:    
    start = "({},{})".format(a, b)
    goal  = "({},{})".format(c, d)

    print("Start: {:<10} Goal: {}".format(start, goal))

Result:

Start: (111,2)    Goal: (14,90)
Start: (46,1)     Goal: (16,111)
Start: (94,1)     Goal: (38,1)

BTW: You can also use grid() to create two columns - one with Radiobutton and Start, second with Label and Goal

Upvotes: 1

Related Questions