Tkinter Radiobutton 中具有指定宽度的垂直对齐字符串

Vertical align string in Tkinter Radiobutton with specified width

我需要帮助在 Tkinter 中对齐字符串 Radiobutton

如您所见,它没有完全对齐。如何使 "Goal" 文本垂直对齐?我是这样做的:

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)

您必须对齐 Start,而不是 Goal - {:<10} - 因此它将始终使用 10 个字符。然后 Goal 将从同一个地方开始。但它只适用于等宽字体

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))

结果:

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

顺便说一句: 您还可以使用 grid() 创建两列 - 一列为 RadiobuttonStart,第二列为 LabelGoal

将文本分成两个小部件:单选按钮和标签。然后将radiobuttons和labels的parent做成frame,用grid排列成两列十行的矩阵。

这是一个粗略的例子:

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()