Reputation: 31567
I'm new to Tkinter and I have some problems getting the desired layout. Here's the code:
import tkinter as tk
class MainFrame(tk.Frame):
def __init__(self, master, w, h):
tk.Frame.__init__(self, master, width=w, height=h)
self.toolpanel = ToolPanel(self, 200, h)
self.toolpanel.pack(side=tk.LEFT, fill=tk.Y)
class ToolPanel(tk.Frame):
def __init__(self, master, w, h):
tk.Frame.__init__(self, master, width=w, height=h, background='#000')
def main():
root = tk.Tk()
root.geometry('640x480')
mainframe = MainFrame(root, 640, 480)
mainframe.pack()
root.mainloop()
Below are the expect layout (right) and the actual layout (left). If I make the root
the master of the tools panel instead of the main frame, then I will get the expected output. But this is not what I want, I think it makes more sense to have the main frame be the master of the tools panel.
self.toolpanel = ToolPanel(self, 200, h) # Actual result
self.toolpanel = ToolPanel(master, 200, h) # Expected (desired) result
I noticed that when I construct the main frame, even though I pass it the width and height, its size is still 1x1
until I call pack()
. How should I organize my Tkinter application better and how can I get the desired result?
class MainFrame(tk.Frame):
def __init__(self, master, w, h):
tk.Frame.__init__(self, master, width=w, height=h)
# At this point, the size is still 1x1
# ...
Upvotes: 2
Views: 2452
Reputation: 385830
The problem isn't that the toolpanel is in the wrong spot, it's that it is inside the mainframe and the mainframe is in the wrong spot.
When you do this:
mainframe.pack()
... Tkinter defaults to side=TOP, fill=NONE
, roughly meaning it will be centered in it's container and stuck to the top. Instead, you want the mainframe to either be along the left edge, or fill the whole container.
Try changing that statement to either of the following two and observe the behavior when the GUI starts up, and when you resize:
mainframe.pack(fill="both", expand=True)
-or-
mainframe.pack(side="left", fill="y")
For extra enlightenment, temporarily change the background of the Mainframe and then try both of the above examples to see what changes. When having layout problems, this is a powerful technique because it helps you visualize whether or not widgets are filling areas that you think they should
Upvotes: 2