Python: Getting started with tk, widget doesn't resize grid?
I'm just getting started with Python Tkinter
/ ttk
and I'm having trouble resizing my widget when using the grid layout. Here is a subset of my code that shows the same problem as the full code (I understand that this subset is so simple that I would probably be better off using pack
instead grid
, but I suppose it will help cut to the main problem, and once i understand i can fix it wherever it goes in my full program):
import Tkinter as tk
import ttk
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
# Create my widgets
self.tree = ttk.Treeview(self)
ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
self.tree.heading('#0', text='Path', anchor='w')
# Populate the treeview (just a single root node for this simple example)
root_node = self.tree.insert('', 'end', text='Test', open=True)
# Lay it out on a grid so that it'll fill the width of the containing window.
self.tree.grid(row=0, column=0, sticky='nsew')
self.tree.columnconfigure(0, weight=1)
ysb.grid(row=0, column=1, sticky='nse')
xsb.grid(row=1, column=0, sticky='sew')
self.grid()
master.columnconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
app = App(tk.Tk())
app.mainloop()
I want to make it so that my tree view fills the full width of the window, but instead the tree view is just centered inside the middle of the window.
source to share
Try giving an argument sticky
when you do self.grid
. Without it, the frame will not change when the window changes. You will also need rowconfigure
master and self, just like you have columnconfigure
d them.
#rest of code goes here...
xsb.grid(row=1, column=0, sticky='sew')
self.grid(sticky="nesw")
master.columnconfigure(0, weight=1)
master.rowconfigure(0,weight=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
Alternatively, instead of gridding Frame, pack
specify it to fill the space it occupies. Since Frame is the only widget in Tk, it really doesn't matter if you have pack
or grid
.
#rest of code goes here...
xsb.grid(row=1, column=0, sticky='sew')
self.pack(fill=tk.BOTH, expand=1)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
source to share