You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Tkinter的pack方法让两个按钮在底部左右并排显示

在Tkinter中用pack方法实现底部左右对齐的按钮

要让两个按钮在窗口底部分别居左和居右,你需要借助一个**容器框架(Frame)**来组织它们——直接给两个按钮设置side="bottom"会导致它们垂直堆叠。具体实现步骤如下:

  1. 创建一个框架,将其打包到窗口底部,并设置fill="x"让框架横向铺满整个窗口宽度。
  2. 将两个按钮放入这个框架中,分别设置side="left"和side="right"实现左右对齐。

修正后的代码示例:

import tkinter as tk
from tkinter import Button

root = tk.Tk()
root.geometry("400x300")  # 设置窗口大小,方便查看效果

# 创建底部容器框架
bottom_frame = tk.Frame(root)
bottom_frame.pack(side="bottom", fill="x", padx=10, pady=10)  # padx/pady增加边距优化视觉

# 创建按钮并放入框架
quit_btn = Button(bottom_frame, text="Quit", font=("Segoe Script", 11), height=1, width=9, bg="indian red")
quit_btn.pack(side="left")

restart_btn = Button(bottom_frame, text="Restart", font=("Segoe Script", 11), height=1, width=9, bg='indian red')
restart_btn.pack(side="right")

root.mainloop()

关键说明:

  • 容器框架bottom_frame通过fill="x"确保占据窗口整个横向宽度,为按钮左右对齐提供空间。
  • 按钮的side参数是相对于所在框架设置的,而非主窗口,因此能实现横向排列。
  • 可通过padx和pady参数给框架或按钮添加额外间距,提升界面美观度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:17:22