Columnspan Widget Throwing Off Columns - python

I'm having trouble getting my first "None" checkbox widget where I want it. Here is a link to a screenshot.
I'm trying to get the "None" checkbox widget to be directly to the right of the Entry widget. The bottom rows containing spinbox widgets are contained within a LabelFrame widget located at row=7, column=2 that has a columnspan of 2. My first checkbox widget is located at row=5, column=3 with sticky='w'. Why then isn't it up against the Entry widget at row=5, column=2 since I gave the LabelFrame a columnspan of 2?
Here is my code:
tk.Label(GUI, text='label 1').grid(row=0, sticky='w')
tk.Label(GUI, text='label 2').grid(row=1, sticky='w')
tk.Label(GUI, text='label 3').grid(row=2, sticky='w')
tk.Label(GUI, text='label 4').grid(row=3, sticky='w')
tk.Label(GUI, text='label 5').grid(row=4, sticky='w')
tk.Label(GUI, text='label 6').grid(row=5, sticky='w')
tk.Label(GUI, text='label 7').grid(row=6, sticky='w')
tk.Label(GUI, text='label 8').grid(row=7, sticky='w')
tk.Label(GUI, text='label 9').grid(row=8, sticky='w')
tk.Label(GUI, text='$').grid(row=2, column=1, sticky='w')
tk.Label(GUI, text='$').grid(row=3, column=1, sticky='w')
tk.Label(GUI, text='$').grid(row=4, column=1, sticky='w')
tk.Label(GUI, text='9999').grid(row=2, column=2, sticky='w')
input1 = tk.Entry(GUI, width=10)
input2 = tk.Entry(GUI, width=10)
input3 = tk.Entry(GUI, width=10)
button_input = tk.Checkbutton(GUI, text='None')
input5 = tk.Entry(GUI, width=10)
date_field = tk.LabelFrame(GUI)
scheduled_start_month_input = tk.Spinbox(date_field, from_=1, to=12, width=2)
scheduled_start_day_input = tk.Spinbox(date_field, from_=1, to=31, width=2)
scheduled_start_year_input = tk.Spinbox(date_field, from_=2018, to=2025, width=4)
scheduled_start_hour_input = tk.Spinbox(date_field, from_=0, to=23, width=2)
scheduled_start_minute_input = tk.Spinbox(date_field, from_=0, to=59, width=2)
start_on_launch_option = tk.Checkbutton(date_field, onvalue=True, offvalue=False, text='On Launch')
scheduled_stop_month_input = tk.Spinbox(date_field, from_=1, to=12, width=2)
scheduled_stop_day_input = tk.Spinbox(date_field, from_=1, to=31, width=2)
scheduled_stop_year_input = tk.Spinbox(date_field, from_=2018, to=2025, width=4)
scheduled_stop_hour_input = tk.Spinbox(date_field, from_=0, to=23, width=2)
scheduled_stop_minute_input = tk.Spinbox(date_field, from_=0, to=59, width=2)
scheduled_stop_none = tk.Checkbutton(date_field, onvalue=True, offvalue=False, text='None')
input1.grid(row=3, column=2, sticky='w')
input2.grid(row=4, column=2, sticky='w')
input3.grid(row=5, column=2, sticky='w')
button_input.grid(row=5, column=3, sticky='w')
input5.grid(row=6, column=2, sticky='w')
date_field.grid(row=7, column=2, rowspan=2, columnspan=2, sticky='w')
scheduled_start_month_input.grid(column=0)
tk.Label(date_field, text='/').grid(column=1, row=0)
scheduled_start_day_input.grid(column=2, row=0)
tk.Label(date_field, text='/').grid(column=3, row=0)
scheduled_start_year_input.grid(column=4, row=0)
tk.Label(date_field, text=' ').grid(column=5, row=0)
scheduled_start_hour_input.grid(column=6, row=0)
tk.Label(date_field, text=':').grid(column=7, row=0)
scheduled_start_minute_input.grid(column=8, row=0)
start_on_launch_option.grid(row=0, column=9)
scheduled_stop_month_input.grid(column=0)
tk.Label(date_field, text='/').grid(column=1, row=1)
scheduled_stop_day_input.grid(column=2, row=1)
tk.Label(date_field, text='/').grid(column=3, row=1)
scheduled_stop_year_input.grid(column=4, row=1)
tk.Label(date_field, text=' ').grid(column=5, row=1)
scheduled_stop_hour_input.grid(column=6, row=1)
tk.Label(date_field, text=':').grid(column=7, row=1)
scheduled_stop_minute_input.grid(column=8, row=1)
scheduled_stop_none.grid(column=9, row=1, sticky='w')
tk.Button(GUI, text='Launch').grid(row=9, sticky='w')
GUI.mainloop()

The problem is that the 2nd column is wider than you think it is. To see it, change the line where you add the input widget to the grid so that it looks like this:
input3.grid(row=5, column=2, sticky='ew')
You'll see that the checkbutton is in fact as far left as it can go, and it is the column to its left that is responsible for all of the extra space.
The reason is because the datefield widget spans two columns, but those two columns aren't wide enough to hold the datefield. grid has to add extra space to the columns so that the widget will fit.
If you want the second column to stay a fixed size and have column 3 to be the one that grows and shrinks, you have to give column 3 a non-zero weight so that grid can allocate all extra space to that column.
You can do that by adding this line of code somewhere:
GUI.grid_columnconfigure(3, weight=1)
Another solution would be to add the weight to an invisible column 4, and then have datefield span three columns instead of two. That will cause columns 2 and 3 to retain their natural size, and any extra space would be given to an empty column.
GUI.grid_columnconfigure(4, weight=1)
date_field.grid(row=7, column=2, rowspan=2, columnspan=3, sticky='w')

Add following code:
GUI.grid_columnconfigure(3, weight=1)
It means that column 3 would occupy all the place it can get. Your/default weight is 0. and that means Checkbutton instance is wide just as "None" text is, so sticky w equals sticky e equals sticky we or wens. If you set the weight to 1 then your sticky argument actually takes place.

Related

Aligning entries/buttons with tkinter

I've been trying to align the entries and buttons on this password manager I built for a while now but haven't been able to find a solution that works.
I tried changing the width, columnspan, and coordinates but it doesn't seem to work.
I want the password entry to be aligned just like the other two but with a lower width so that the generate button does not go over. I also want the add button to be aligned equally with the row and column.
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(width=200, height=200)
my_pass_img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=my_pass_img)
canvas.grid(column=1, row=0)
web_label = Label(text="Website:", fg="black")
web_label.grid(row=1, column=0)
user_label = Label(text="Email/Username:", fg="black")
user_label.grid(row=2, column=0)
pass_label = Label(text="Password:", fg="black")
pass_label.grid(row=3, column=0)
web_entry = Entry(width=35)
web_entry.grid(row=1, column=1, columnspan=2)
web_entry.focus()
user_entry = Entry(width=35)
user_entry.grid(row=2, column=1, columnspan=2)
user_entry.insert(0, "-#gmail.com")
pass_entry = Entry(width=30)
pass_entry.grid(row=3, column=1)
generate_button = Button(text="Generate Password", fg="black", command=generate_password)
generate_button.grid(row=3, column=2)
add_button = Button(width=36, text="Add", fg="black", command=save)
add_button.grid(row=4, column=1, columnspan=2)
window.mainloop()
Grid
When using grid to setup your widgets, the entire window is divided into individual cells based on the number of columns and rows you've specified. Although you can control the individual sizes of widgets, the overall size it can take will be limited by your choice of column- and rowwidth, as well as column- and rowspan.
Sticky
You can use the sticky attribute in grid to set the side of the column you want your widgets to 'stick' to.
The stickiness is set by choosing one of the 8 directions on a compass:
N (north): stick to top of cell
S (south): bottom
E (east): right
W (west): left
NW, NE, SW, SE: top-left, top-right, bottom-left, bottom-right corners respectively.
There are also two bonus stickiness options:
NS: stretch your widget from top to bottom of the sell, but keep it centered horizontally
EW: stretch from left to right of the cell, but centered vertically.
Padding
To increase legibility, you can add padding above and below, and to the sides, of your widgets using the padx and pady attributes (measured in pixels).
So if you set stickyness to "W" with a horizontal padding padx=5, the widget position is offset from the cell boundary by 5 pixels.
Combining it in your example
To align the entries, set their sticky attribute to "W", or tk.W, to algin on left side of cell.
If you want to align labels on the right set sticky="E".
You can reduce the columnspan too of the entries, if you don't need them to be extra large. The resulting changes to grid are thus:
canvas.grid(column=1, row=0)
# Label widgets: set sticky to 'East'
web_label.grid(row=1, column=0, sticky='E')
user_label.grid(row=2, column=0, sticky='E')
pass_label.grid(row=3, column=0, sticky='E')
# Entry widgets
web_entry.grid(row=1, column=1, columnspan=1, sticky='WE')
user_entry.grid(row=2, column=1, columnspan=1, sticky=tk.EW) # Note flag is available as tkinter attribute
# Password entry: align on left-hand side
pass_entry.grid(row=3, column=1, sticky='W')
# Align button to right side of 3rd column
generate_button.grid(row=3, column=2,sticky='E')
# Can either align in middle column...
add_button.grid(row=4, column=1, columnspan=1, sticky="WE")
#... or in middle of page
add_button.grid(row=4, column=0, columnspan=3, sticky="WE")
Bonus
Apply padding (or sticky) to all widgets in a frame or window:
for child in window.winfo_children():
child.grid_configure(padx=3, pady=3)
# child.grid_configure(sticky='W')
You can use sticky option to put the widget in a grid cell at "n" (north), "s" (south), "e" (east) and "w" (west). If not specify, it is by default is "" which will put the widget at the center of the cell.
For your case, add sticky="w" to all the labels and entries, and sticky="e" to the "Add" button:
from tkinter import *
def generate_password():
pass
def save():
pass
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(window, width=200, height=200)
my_pass_img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=my_pass_img)
canvas.grid(column=1, row=0)
web_label = Label(window, text="Website:", fg="black")
web_label.grid(row=1, column=0, sticky="w")
user_label = Label(window, text="Email/Username:", fg="black")
user_label.grid(row=2, column=0, sticky="w")
pass_label = Label(window, text="Password:", fg="black")
pass_label.grid(row=3, column=0, sticky="w")
web_entry = Entry(window, width=35)
web_entry.grid(row=1, column=1, columnspan=2, sticky="w")
web_entry.focus()
user_entry = Entry(window, width=35)
user_entry.grid(row=2, column=1, columnspan=2, sticky="w")
user_entry.insert(0, "-#gmail.com")
pass_entry = Entry(window, width=30)
pass_entry.grid(row=3, column=1, sticky="w")
generate_button = Button(window, text="Generate Password", fg="black", command=generate_password)
generate_button.grid(row=3, column=2)
add_button = Button(window, width=36, text="Add", fg="black", command=save)
add_button.grid(row=4, column=1, columnspan=2, sticky="e")
window.mainloop()
Result:
You can play around with different values or combinations of them of the sticky option to see the different effects.
Note also that it is better to specify the parent of those widgets.

How to get only a corresponding entry box regardless of how many times I change radiobutton?

from tkinter import *
win=Tk()
var = StringVar()
l = Label(win, bg='white', width=15)
l.grid(row=17,column=1,padx=10, pady=10, sticky='w')
def print1_selection():
if var.get()=="Number":
lab1= Label(win, text="Enter a number").grid(row=4, column=0)
ent1=Entry(win).grid(row=4, column=1)
l.config(text='you have selected ' + var.get())
elif var.get()=="Alphabet":
lab21= Label(win, text="Enter an alphabet").grid(row=5, column=0)
ent21=Entry(win).grid(row=5, column=1)
l.config(text='you have selected ' + var.get())
lbl4=Label(win, text="Select One", bg="crimson", fg="white", font=("times new
roman",15,"bold")).grid(row=1, column=0, padx=10, pady=10, sticky='w')
r1 = Radiobutton(win, text='Number',variable=var, value='Number', command=print1_selection, width=22)
r1.grid(row=2,column=0,padx=10, pady=10)
r2 = Radiobutton(win, text='Alphabet', variable=var, value='Alphabet', command=print1_selection, width=22)
r2.grid(row=2,column=1,padx=10, pady=10)
win.mainloop()
In this code I want that when I select radiobutton number, only enter a number should appear and same for the other.
But the problem is that when I select number after selecting alphabet, it shows both. I need only the selected one and eliminate the other instantly.
This is how I would approach this issue:
from tkinter import Tk, StringVar, Label, Frame, Entry, Radiobutton
def print1_selection():
for widget in entry_frame.winfo_children():
widget.destroy()
value = var.get()
lbl.config(text='You have selected ' + value)
if value == "Number":
Label(entry_frame, text="Enter a number").grid(row=0, column=0)
Entry(entry_frame).grid(row=0, column=1)
elif value == "Alphabet":
Label(entry_frame, text="Enter an alphabet").grid(row=0, column=0)
Entry(entry_frame).grid(row=0, column=1)
win = Tk()
var = StringVar(value=0)
entry_frame = Frame(win)
entry_frame.grid(row=2, column=0, columnspan=2)
lbl = Label(win, bg='white', width=20)
lbl.grid(row=3, column=0, columnspan=2, padx=10, pady=10, sticky='w')
Label(win, text="Select One", bg="crimson", fg="white", font=("times new roman", 15, "bold")).grid(row=0, column=0, padx=10, pady=10, sticky='w')
Radiobutton(win, text='Number', variable=var, value='Number', command=print1_selection, width=22).grid(row=1, column=0, padx=10, pady=10)
Radiobutton(win, text='Alphabet', variable=var, value='Alphabet', command=print1_selection, width=22).grid(row=1, column=1, padx=10, pady=10)
win.mainloop()
As You can see if You don't plan on using the widgets instance anywhere You don't have to assign it to a variable. Also no need to configure label in both statements since that will be done anyways so just do it at the beginning, also rows start from 0 too. Frames help with organizing widgets. Also if You want neither of the radiobuttons selected set the variable to 0.

Cannot resize the Tkinter buttons when using Sticky

I'm trying to adjust the buttons, but somehow even after changing the width, it won't change the size. This is my code:
if __name__ == '__main__':
# create application window
app = Tk()
# title
app.title("Music Players")
# geometry
app.geometry('500x300')
# background color
app.configure(bg='orange')
equation = StringVar()
window_1 = Label(app, textvariable=equation)
window_1.grid(columnspan=3, ipadx=100, ipady=10)
equation.set('music player')
window_2 = Entry(app, width=30)
window_2.grid(columnspan=5, ipadx=100, ipady=10)
# Create buttons and other accessories
button1 = Button(app, text='PLAY', fg='yellow', bg='purple',
command=lambda: press('PLAY'), height=2, width=1)
button1.grid(row=2, column=0, sticky="NSEW")
button2 = Button(app, text='STOP', fg='yellow', bg='purple',
command=lambda: press('STOP'), height=2, width=2)
button2.grid(row=2, column=1, sticky="NSEW")
button3 = Button(app, text='NEXT', fg='yellow', bg='purple',
command=lambda: press('NEXT'), height=2, width=2)
button3.grid(row=2, column=2, sticky="NSEW")
button4 = Button(app, text='PREVIOUS', fg='yellow', bg='purple',
command=lambda: press('PREVIOUS'), height=2, width=2)
button4.grid(row=2, column=3, sticky="NSEW")
I'm assuming it is because of sticky="NSEW", because when I remove it, the buttons change the size, but there is big spaces between the buttons and also, very spaced out, even though columns=0 and columns=1.
How can I change the size of buttons without getting rid of sticky? Or, without sticky, but having the buttons next to each other?
My expected output will be like this:
Thank you in advance!

TKinter: lost alignment between frame and root

I am running into a curious problem. I have a small grid (8 rows, 5 columns). Root with a couple of frames. Most run fine. Four fields of the the top row (1 in my case, I do not use 0) have a text and must have the same color continuously. I could not realise this in root itself so I made a frame (text=""), with labels. That gives the desired look apart from the fact that all the texts are concatenated at the left and no longer above the gridfields below.
The code is realy very simple but I expect it will be requested anyway so here is the relevant part:
# Top frame
top_frame=LabelFrame(root, text= "", bg=top_line_color)
top_frame.grid(row =1, column=0, sticky=W+E, columnspan=5)
# Fixed labels:
Label(top_frame, text="Anten", font=fnt, bg=top_line_color).grid(row=1,
column=0)
Label(top_frame, text="Antenna", font=fnt, bg=top_line_color).grid(row=1,
column=1)
Label(top_frame, text="Corr.", font=fnt, width=4,
bg=top_line_color).grid(row=1, column=3)
Label(top_frame, text="Move", font=fnt, width=4,
bg=top_line_color).grid(row=1, sticky=W, column=4)
Label(root, text="Azimuth:", justify=RIGHT, font=fnt).grid(row=2, sticky=W)
Label(root, text="Elevation:", justify=RIGHT, font=fnt).grid(row=3,
sticky=W)
Label(root, text="Location:",justify=RIGHT, font=fnt).grid(row=4, sticky=W)
Label(root, text=acemedat.myloc, font=fnt).grid(row=4, column=1)
Label(root, text="Dat/Tim:", justify=RIGHT, font=fnt).grid(row=4, column=2)
Label(root, text="Moon distance (km):", font=fnt).grid(row=5, columnspan=2,
sticky=W)
The labels are followed by data fields (in root as well). They comply with the grid without problem.
What can I do to to align the frame fields with the root fields?
Many thanks in advance,
Harke
If you want everything to line up in a grid, the easiest solution is to put them all in the same frame. If you use the sticky attribute for the fixed labels, you can have a solid, unbroken color. Depending on your system, you might need to change the labels to have a borderwidth and/or highlightthickness of zero. If you want the labels to be left-aligned, you can do that with the anchor attribute of the labels.
For example:
from tkinter import *
root = Tk()
fnt = ("Helvetica", "12")
top_line_color = "bisque"
# Fixed labels:
Label(root, text="Anten", font=fnt, bg=top_line_color,
anchor="w").grid(row=0, column=0, sticky="nsew")
Label(root, text="Antenna", font=fnt, bg=top_line_color,
anchor="w").grid(row=0, column=1, sticky="nsew")
Label(root, text="Corr.", font=fnt, width=4, bg=top_line_color,
anchor="w").grid(row=0, column=2, sticky="nsew")
Label(root, text="Move", font=fnt, width=4, bg=top_line_color,
anchor="w").grid(row=0, column=3, sticky="nsew")
Label(root, text="Azimuth:", justify=RIGHT, font=fnt).grid(row=2, sticky=W)
Label(root, text="Elevation:", justify=RIGHT, font=fnt).grid(row=3, sticky=W)
Label(root, text="Location:",justify=RIGHT, font=fnt).grid(row=4, sticky=W)
Label(root, text="acemedat.myloc", font=fnt).grid(row=4, column=1)
Label(root, text="Dat/Tim:", justify=RIGHT, font=fnt).grid(row=4, column=2)
Label(root, text="Moon distance (km):", font=fnt).grid(row=5, columnspan=2, sticky=W)
root.mainloop()

tkinter ListBox and Label position

I am little bit comfused with grid system in tkinter Python. Can anyone show how to make it in right way?! ListBox and Label items positions are not in the places where I expexted to see them.
CODE:
self.third_label = Label(self, text="TEXT")
self.third_label.grid(row=2, column=0, columnspan=4, padx=10, pady=10, sticky=W)
self.fourth_label = Label(self, text="LONG TEXT")
self.fourth_label.grid(row=2, column=1, columnspan=4, padx=10, pady=10, sticky=W)
self.fifth_label = Label(self, text="SOME TEXT")
self.fifth_label.grid(row=2, column=2, columnspan=6, padx=10, pady=10, sticky=W)
self.sixth_label = Label(self, text="BIG TEXT")
self.sixth_label.grid(row=2, column=3, columnspan=4, padx=10, pady=10, sticky=W)
self.first_listbox = Listbox(self, width=40, selectmode=EXTENDED)
self.first_listbox.grid(row=3, column=0, columnspan=4, padx=10, pady=10, sticky=W)
self.second_listbox = Listbox(self, width=40, selectmode=EXTENDED)
self.second_listbox.grid(row=3, column=2, columnspan=4, padx=10, pady=10, sticky=W)
self.third_listbox = Listbox(self, width=40, selectmode=EXTENDED)
self.third_listbox.grid(row=3, column=4, columnspan=4, padx=10, pady=10, sticky=W)
self.fourth_listbox = Listbox(self, width=40, selectmode=EXTENDED)
self.fourth_listbox.grid(row=3, column=6, columnspan=4, padx=10, pady=10, sticky=W)
What I have right now:
Just Example:
The grid system works fine. The problem is your columnspans, which don't make much sense. You're gridding the widgets into certain column positions then giving them a columnspan that is beyond the range of where the next widget is to be gridded so on and so forth.
Small example:
import string
import tkinter as tk
root = tk.Tk()
for i in range(3):
tk.Label(root, text=string.ascii_letters).grid(row=0, column=i)
tk.Listbox(root, width=40).grid(row=1, column=i)
root.mainloop()
Edit from comments (for listbox size):
To get the number of lines in a listbox you can use the .size() method.
Image:

Categories