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

2024-03-28 09:04:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Window

正如你所看到的,它不是完全对齐的。如何使“目标”文本垂直对齐?我是这样做的:

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)

Tags: textinfortkintermoderangepackjoin
2条回答

您必须对齐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))

结果:

^{pr2}$

顺便说一句:您还可以使用grid()来创建两个列-一个是Radiobutton和{},第二个是Label和{}

将文本分为两个小部件:单选按钮和标签。然后使单选按钮和标签的父对象成为一个框架,并使用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()

相关问题 更多 >