Tkinter 按钮不在左侧堆叠

Tkinter buttons not stacking on left

我想在框架的左侧(不是中间)堆叠两个按钮。

我的代码:

import tkinter as tk
from tkinter import Frame, Button, LEFT

def pressed():
    print("Button Pressed!")


root = tk.Tk()

frame = Frame(root)
frame.pack()

button1 = Button(frame, text="Button1", command=pressed)
button1.pack(side=LEFT, pady=20)

button2 = Button(frame, text="Button2", command=pressed)
button2.pack(side=LEFT, ipadx=20)


root.mainloop()

我也试过:

button1.pack(side=LEFT, fill='x' pady=20)

但它不会改变输出中的任何内容。

所需输出:

  +------------------------------+
  |    |(20px)                   |
  |[Button1] <------------------ |
  |    |(20px)                   |
  |[-(20px)-Button2-(20px)-] <-- |
  |                              |
  |                              |
  +------------------------------+

代码中的其他一切都很好,我只希望两个按钮都堆叠在框架的左侧。

我也尝试过 解决方案,但它会将按钮放在中间。

注意:我不能使用gridplace

您的框架仅打包,没有任何 expandfill 参数,因此您的按钮将保留在顶部中央,因为框架只会扩展到足以容纳按钮而不会更多。因此,为了让按钮出现在左侧,您需要这样的东西。

import tkinter as tk
from tkinter import Frame, Button, LEFT

def pressed():
    print("Button Pressed!")


root = tk.Tk()

frame = Frame(root)
frame.pack(expand=True, fill=tk.BOTH) #control the frame behavior

button1 = Button(frame, text="Button1", command=pressed)
button1.pack(side=tk.TOP, anchor=tk.W, pady=20)# pack top and left

button2 = Button(frame, text="Button2", command=pressed)
button2.pack(side=tk.TOP, anchor=tk.W)


root.mainloop()

或者不太理想的方法,设置帧大小并防止它像这样传播。

import tkinter as tk
from tkinter import Frame, Button, LEFT

def pressed():
    print("Button Pressed!")


root = tk.Tk()

frame = Frame(root, height=1000, width=1000)
frame.pack()
frame.pack_propagate(0) #stops the frame from shrinking to fit widgets

button1 = Button(frame, text="Button1", command=pressed)
button1.pack(side=tk.TOP, anchor=tk.W, pady=20)

button2 = Button(frame, text="Button2", command=pressed)
button2.pack(side=tk.TOP, anchor=tk.W)


root.mainloop()