对齐 Tkinter 单选按钮

Align Tkinter radio buttons

我的 Tkinter 单选按钮未对齐。我试过这个Python tkinter align radio buttons west, this Python tkinter align radio buttons west,其中none有效,我看到的是这个

当我使用网格来管理小部件时(必须是网格,因为它是更大 UI 的一部分)。

我已经尝试过锚点和证明,但得到的回溯表明这些是不允许的:

回溯

Traceback (most recent call last):
  File "/Users/.../Desktop/tk_gui_grid/temp_1243.py", line 14, in <module>
    tk.Radiobutton(root, text='T_Deviation', padx = 20, variable=value, command=get_traj_method, value=0).grid(row=1, anchor=tk.E)
  File "/Users/.../opt/anaconda3/lib/python3.7/tkinter/__init__.py", line 2226, in grid_configure
    + self._options(cnf, kw))
_tkinter.TclError: bad option "-anchor": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
(base) ... tk_gui_grid % /Users/.../opt/anaconda3/bin/python /Users/.../Desktop/tk_gui_grid/temp_1243.py


Traceback (most recent call last):
  File "/Users/.../Desktop/tk_gui_grid/temp_1243.py", line 14, in <module>
    tk.Radiobutton(root, text='T_Deviation', padx = 20, variable=value, command=get_traj_method, value=0).grid(row=1, justify=tk.E)
  File "/Users/.../opt/anaconda3/lib/python3.7/tkinter/__init__.py", line 2226, in grid_configure
    + self._options(cnf, kw))
_tkinter.TclError: bad option "-justify": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky

代码

import tkinter as tk

root = tk.Tk()

value = tk.IntVar()
value.set(0)  # initializing the choice, i.e. mrads


def get_traj_method():
    print(value.get())

tk.Label(root, text="""T method:""", justify = tk.LEFT, padx = 20).grid(row=0)

tk.Radiobutton(root, text='T_Deviation', padx = 20, variable=value, command=get_traj_method, value=0).grid(row=1, sticky=tk.E)
tk.Radiobutton(root, text='T_Degrees', padx = 20, variable=value, command=get_traj_method, value=1).grid(row=2, sticky=tk.E)

root.mainloop()

将 sticky = "W" 代替 tk.E(tk.W 应该也可以)

小部件有不同的大小,所以当它们向东(右)锁定时,两端对齐,但开头(在本例中为按钮)不会对齐。

当把sticky = "W" 的时候,情况正好相反。 :

import tkinter as tk

root = tk.Tk()

value = tk.IntVar()
value.set(0)  # initializing the choice, i.e. mrads


def get_traj_method():
    print(value.get())

tk.Label(root, text="T method:", justify = tk.LEFT).grid(row=0)

tk.Radiobutton(root, text='T_Deviation', variable=value, command=get_traj_method, value=0).grid(row=1, sticky="W")
tk.Radiobutton(root, text='T_Degrees', variable=value, command=get_traj_method, value=1).grid(row=2, sticky="W")

root.mainloop()