You need to enable JavaScript to run this app. 如何在Python Tkinter中对齐相邻行列的Radiobutton单选按钮
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Tkinter中对齐相邻行列的Radiobutton单选按钮

问题原因

你当前直接将所有Radiobutton绑定在root窗口并调用pack()方法,pack布局默认按组件添加顺序从上到下垂直堆叠,无法实现多列并排效果。anchor参数仅能控制组件在自身分配空间内的对齐方向,无法修改整体排列逻辑。

实现方案

先创建3个独立的Frame容器作为列容器,将3个Frame水平并排排列,再将对应组的单选按钮放入对应Frame中,分别设置对齐规则即可:

  • 设备组所在列内部单选按钮靠右对齐
  • 数据源组所在列内部单选按钮靠左对齐
  • 环境组所在列内部单选按钮居中对齐
修改后代码示例
from tkinter import Tk, StringVar, Radiobutton, Frame

root = Tk()
# 可根据实际需求调整窗口尺寸
root.geometry("400x200")

# 初始化三个水平并排的列容器
col_device = Frame(root)
col_device.pack(side="left", fill="both", expand=True, padx=8)

col_source = Frame(root)
col_source.pack(side="left", fill="both", expand=True, padx=8)

col_env = Frame(root)
col_env.pack(side="left", fill="both", expand=True, padx=8)

# 第一列:设备组,靠右对齐
selected_device = StringVar()
devices = ['CAN', 'US', 'EU', 'AU']
for device in devices:
    r = Radiobutton(
        col_device,
        text=device,
        value=device,
        variable=selected_device
    )
    r.pack(anchor="e", pady=2)

# 第二列:数据源组,靠左对齐
selected_source = StringVar()
sources = ['Raw Data', 'Encoded Data']
for source in sources:
    r = Radiobutton(
        col_source,
        text=source,
        value=source,
        variable=selected_source
    )
    r.pack(anchor="w", pady=2)

# 第三列:环境组,居中对齐
selected_environment = StringVar()
environments = ['Sprint', 'RC', 'Staging']
for environment in environments:
    r = Radiobutton(
        col_env,
        text=environment,
        value=environment,
        variable=selected_environment
    )
    r.pack(anchor="center", pady=2)

root.mainloop()

内容的提问来源于stack exchange,提问作者ENV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 01:45:04