So I'm trying to create a basic text-entry thing to understand the basics of Tkinter, but when I try and grid something, if the column or row is greater than 1, it will act as if it is 1
Here is my code:
from tkinter import *
window = Tk()
window.minsize(width=500, height=300)
# label
my_label = Label(text="Text", font=("Consolas", 24, "bold"))
my_label["text"] = "New Text"
my_label.config(text="New Text")
# my_label.pack() # adding keyword parameters such as "expand=True" or "side='left'" can affect where it is positioned
# my_label.place(x=100, y=40)
my_label.grid(column=10, row=15)
# Button
def button_clicked():
my_label["text"] = input.get()
button = Button(text="Click Me", command=button_clicked)
button.grid(row=1, column=1)
# Entry
input = Entry(width=10)
window.mainloop()
Now I want the label to be about 3/4 of the way across the screen, and as you see, I use (for the label) column 10 and row 15. Still, when I try and run this, the label will only go diagonally down from the button. Is this how Tkinter is supposed to work, or am I just doing it wrong? I would appreciate any help.
yes, that's basically how tkinter works, it is at column 10, it's just that columns 2-9 all have zero width as they contain nothing, so you end up seeing only 2 columns.
to make something "centered" you need to have its "bounding box" scale with the containing "frame" using grid_columnconfigure
from the Tk official grid tutorial
my_label.grid(column=10, row=15)
window.grid_columnconfigure(10,weight=1) # column 10 will grow
window.grid_rowconfigure(15,weight=1) # row 15 will grow
this allows the bounding box to grow and the label will remain centered as it is not set to stick to any corner, but it is offset by the button.
but if you really wanted it to be in the exact center then you can make the label span more columns than the button.
my_label.grid(column=1,columnspan=2, row=2) # label spans columns 1 and 2
window.grid_columnconfigure(2,weight=1) # column 2 will grow
window.grid_rowconfigure(2,weight=1) # row 2 will grow.
you get the required result.
but now we want both the button and the label to be centered, we can set them both in the same column that is set to grow with the size of the window, and make both rows grow to fit the entire window.
my_label.grid(column=1,columnspan=2, row=2, sticky="N")
window.grid_columnconfigure(1,weight=1)
window.grid_rowconfigure([1,2],weight=1)
simply playing with grid_columnconfigure
and column
and columnspan
and sticky
and their row counterparts is usually enough to get any shape you want on any screen scale if you add some padding.