Python:tk入门,小部件未在网格上调整大小? [英] Python: Getting started with tk, widget not resizing on grid?
问题描述
我刚开始使用Python的Tkinter
/ttk
,在使用网格布局时,无法调整窗口小部件的大小时遇到了问题.这是我的代码的一个子集,与完整代码存在相同的问题(我意识到这个子集非常简单,我可能最好使用pack
而不是grid
,但是我认为这将有助于切入到主要问题,一旦我了解了,我就可以在完整程序中的任何地方修复它):
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.
推荐答案
在执行self.grid
时,尝试指定sticky
参数.没有它,当窗口打开时,Frame不会调整大小.您还需要rowconfigure
掌握和掌握自我,就像您columnconfigure
掌握了它们一样.
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 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)
或者,而不是将框架网格化,而是pack
,并指定它填充其占用的空间.由于Frame是Tk中唯一的窗口小部件,因此pack
或grid
都没有关系.
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)
这篇关于Python:tk入门,小部件未在网格上调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!