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

如何使用Tkinter将按钮垂直堆叠在窗口右侧

问题:让Tkinter按钮在窗口右侧上下堆叠排列

用户提供的代码如下:

from tkinter import *
root = Tk()

"root.attributes('-alpha', 0.3)"
root.attributes('-fullscreen', True)
root.attributes("-topmost", True)
root.wm_attributes("-transparentcolor", "grey")
root.configure(bg='grey')

def btn_command():
    print("Hallo")

class btn:
  def __init__(self, name, command):
    button = Button(root, text=name, command=command)
    button.config(height=10, width=10)
    button.pack(side=RIGHT)

btn("Clicker1", btn_command)
btn("Clicker2", btn_command)
btn("Clicker3", btn_command)

root.mainloop()

当前按钮会在窗口右侧横向排列,需求是让按钮在窗口右侧上下垂直堆叠。


解决方案

方法1:直接修改pack参数

将按钮的pack(side=RIGHT)改为pack(side=TOP, anchor='e', pady=5):

  • side=TOP:让按钮在父容器中从上到下垂直排列
  • anchor='e':设置按钮靠右对齐,保持在窗口右侧
  • pady=5:添加垂直间距,避免按钮拥挤

修改后的类代码:

class btn:
  def __init__(self, name, command):
    button = Button(root, text=name, command=command)
    button.config(height=10, width=10)
    button.pack(side=TOP, anchor='e', pady=5)

方法2:使用Frame容器(更灵活)

先创建一个靠右的Frame容器,再把按钮放入其中垂直排列,适合后续扩展更多按钮:

from tkinter import *
root = Tk()

"root.attributes('-alpha', 0.3)"
root.attributes('-fullscreen', True)
root.attributes("-topmost", True)
root.wm_attributes("-transparentcolor", "grey")
root.configure(bg='grey')

def btn_command():
    print("Hallo")

# 创建右侧容器,固定在窗口右侧
right_frame = Frame(root, bg='grey')
right_frame.pack(side=RIGHT, fill=Y, padx=10, pady=10)

class btn:
  def __init__(self, name, command):
    button = Button(right_frame, text=name, command=command)
    button.config(height=10, width=10)
    button.pack(side=TOP, pady=5)

btn("Clicker1", btn_command)
btn("Clicker2", btn_command)
btn("Clicker3", btn_command)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:50:40