I want to stack two buttons on the frame's left (NOT MIDDLE).
My code:
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()
I have also tried:
button1.pack(side=LEFT, fill='x' pady=20)
but it does not change anything in output.
Required output:
------------------------------
| |(20px) |
|[Button1] <------------------ |
| |(20px) |
|[-(20px)-Button2-(20px)-] <-- |
| |
| |
------------------------------
Everything else is fine in code, I just want both buttons to be stacked in the LEFT of the frame.
I have also tried this solution but it's placing buttons in the middle.
Note: I can not use grid
or place
.
CodePudding user response:
Your frame only packs, without any expand
or fill
parameter so your buttons are going to stay in the top center because the frame will only expand enough to fit the buttons and no more. So in order for the buttons to appear on the left you would need something like this.
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()
Or a less desireable way, set the frame size and prevent it from propagating like so.
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()