Python:tk入门,窗口小部件没有在网格上调整大小?

问题描述:

我刚刚开始使用Python的Tkinter/ttk,我在使用网格布局时遇到问题,无法调整我的小部件的大小。这是我的代码的一个子集,展示与完整代码相同的问题(我意识到这个子集非常简单,我可能会更好使用pack而不是grid,但我认为这将有助于切入主要问题有一次我明白,我可以修复它无处不在我的全程序中出现):Python:tk入门,窗口小部件没有在网格上调整大小?

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() 

我想让它让我的树视图填补它在窗口的整个宽度,而是树视图正好在窗户中间居中。

+0

我猜你的意思是在第一行输入“Tkinter as tk”? – Kevin 2014-09-19 18:38:08

+0

@凯文 - 对。有趣的事情:我手动编写了前3行代码,之后才想到“我最好只是复制并粘贴以避免犯错误”,然后复制并粘贴剩下的部分。 – ArtOfWarfare 2014-09-19 19:45:23

尝试在self.grid处指定sticky参数。没有它,框架不会调整窗口的大小。你还需要rowconfigure主人和自己,就像你有columnconfigure他们一样。

#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) 

另一方面,不是网格框架,pack并指定它填充它占用的空间。由于Frame是Tk中唯一的小部件,因此无论您是pack还是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) 
+0

感谢Kevin!你是对的,我只需要改变它,让它开始调整窗口的大小就可以在'sticky ='nsew''中添加'self.grid()'的参数。正如我在问题中所说的那样,这只是我的代码的一个最小子集,它演示了我所遇到的问题 - 我的实际程序的布局更多地使'grid()'更适合'pack()'。但修复这条线可以修复我的完整程序中的所有缩放比例。再次感谢! – ArtOfWarfare 2014-09-19 19:49:10