Python: Getting started with tk, widget not resizi

2019-07-02 00:51发布

问题:

I'm just getting started with Python's Tkinter/ttk and I'm having issues getting my widgets to resize when I use a grid layout. Here's a subset of my code which exhibits the same issue as the full code (I realize that this subset is so simple that I'd probably be better off using pack instead of grid, but I figure this will help cut through to the main problem and once I understand, I can fix it everywhere it occurs 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 entire width of the window it's in, but instead the tree view is just centering itself in the middle of the window.

回答1:

Try specifying the sticky argument when you do self.grid. Without it, the Frame won't resize when the window does. You'll also need to rowconfigure master and self, just as you have columnconfigured 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 the Frame, pack it and specify that it fills the space it occupies. Since the Frame is the only widget in the Tk, it doesn't really matter whether you 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)