Question

When I run the following code the created labels appear over top of the Entry boxes as if they are not being added to the same grid.

class Application(Frame):
    def __init__(self,master):
        super(Application,self).__init__(master)
        self.grid()
        self.new_intervals()

    def new_intervals(self):
        self.int_label = Label(text="Interval Name")
        self.int_label.grid(row=0, column=0,sticky=W)
        self.int_time_label = Label(text="Time (HH:MM:SS)")
        self.int_time_label.grid(row=0, column=1,sticky=W)
        self.box1 = Entry(self)
        self.box1.grid(row=1,column=0,sticky=W)
        self.box2 = Entry(self)
        self.box2.grid(row=1,column=1,sticky=W)
        self.box3 = Entry(self)
        self.box3.grid(row=2,column=0,sticky=W)
        self.box4 = Entry(self)
        self.box4.grid(row=2,column=1,sticky=W)


root = Tk()
root.title("Interval Timer")
root.geometry("400x500")
app=Application(root)
root.mainloop() 

I know that i can add these boxes in a loop, however, I can't get it to work without the loop at the moment

Was it helpful?

Solution

  • The application frame is in row 0, column 0 of the main window. That is the default when you don't specify anything. Also as a default, they appear in the middle
  • This frame has four entry widgets spread across two rows, making the frame grow to fit around those entry widgets
  • The "Interval Name" label is also being placed in row 0, column 0 of the main window, because that's what you explicitly tell it to do, and because its parent is the main window.
  • The "Time" label is also in row 0 of the main window because, again, it's parent is the main window
  • both of these labels are appearing in the vertical center of the row because that is the default behavior which you haven't overridden, which is why they appear on top of the entry widgets.

So, because the labels and the application frame are in the same row of the main window, and because the labels default to being in the vertical center, they appear to be in the middle of the entry widgets.

I assume you intended for the labels to be children of the frame, so you need to specify "self" as the first parameter when creating them:

self.int_label = Label(self, text="Interval Name")
...
self.int_time_label = Label(self, text="Time (HH:MM:SS)")

I also recommend grouping all of your grid statements for a particular master window together, so it's easier to see the organization of your widgets. In my experience this makes the code easier to read and easier to maintain.

For example:

self.int_label = Label(...)
self.int_time_label = Label(...)
self.box1 = Entry(...)
...
self.int_label.grid(...)
self.int_time_label.grid(...)
self.box1.grid(...)
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top