Reputation: 874
I am doing a simple UI with TkInter in Python. I want a button at the top left, so I did something like
back = Button(explorer, text="Back")
back.pack(side="top", anchor="w")
where explorer
is a frame, and I expected to see the button on top left, but it's stuck in the center. Any suggestions? I already tried to add side=TOP
but it didn't work. What's the right way to do that?
Upvotes: 0
Views: 4017
Reputation: 88
As mentioned above, your parent frame should fill the x space. This is an example of the parent frame not filling x:
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
element = tk.Frame(root)
element.pack() # No fill
tk.Button(element, text='No Fill').pack(anchor='w')
# To show the fill
tk.Label(root, text='Fill X', bg='green').pack(fill='x')
root.mainloop()
And the result is the button is in the center despite the anchor: https://i.sstatic.net/DAgmH.png
But, make this change:
element.pack(fill='x')
And now your button will be in the top left like here: https://i.sstatic.net/HoGGj.png
Upvotes: 1
Reputation: 330
Tkinter has 3 modules to set items: .pack which puts everything more or less random .grid where you can define the row and column .place where you define everything in pixels
so you could use something like
import tkinter as tk
from tkinter import *
root = Tk()
button = Button(text = 'back')
button.grid(row = 1, column = 1)
root.mainloop()
This shows how to use the .grid function. Keep in mind that the size of each grid is defined by its largest content. If you have a long entry field , the column its placed in is going to be as wide as the entry.
you could also use the .place function, but this one requires the most work. For me its always guessing and rerunning until im happy with it.
import tkinter as tk
from tkinter import *
root = Tk()
button = Button(text = 'back')
root.geometry("150x100")
button.place(x=30, y=30)
root.mainloop()
So in summary, use .pack if you dont care, .grid if you want some kind of control and .place if you want to be accurate. And keep in mind to use only ONE at a time.
Upvotes: 0
Reputation: 3957
Your frame has to occupy all the horizontal space if you want to align its children. Something like (if you imported tkinter elements with from tkinter import *
):
explorer.pack(fill=X)
Upvotes: 0