Python tkinter 文本小部件使用网格填充固定大小的框架
问题描述:
在 Raspberry Pi 上运行 Python 3.4.2 和 Tkinter 8.6.我想使用网格布局管理器创建一个填充固定大小框架的文本小部件.
Running Python 3.4.2 and Tkinter 8.6 on a Raspberry Pi. I want to create a Text widget that fills a fixed sized frame using the grid layout manager.
如果您运行下面的代码,您将看到文本小部件未填充 800x600 帧.我意识到我可以设置 Text 的宽度和高度属性来填充框架,但这只能使用默认字体,不能完全填充框架.
If you run the code below, you'll see the Text widget doesn't fill the 800x600 frame. I realize I could set the Text's width and height attributes to fill the frame, but this would only work default font and wouldn't fill the frame exactly.
from tkinter import *
class Test(Tk):
def __init__(self):
super().__init__()
self.text = frameText(self)
self.geometry('{}x{}'.format(800, 600))
def frameText(frame, **kw):
ysb = Scrollbar(frame)
xsb = Scrollbar(frame, orient = HORIZONTAL)
text = Text(frame, **kw)
ysb.configure(command = text.yview)
xsb.configure(command = text.xview)
text.configure(yscrollcommand = ysb.set, xscrollcommand = xsb.set)
text.grid(row = 0, column = 0, sticky = N+E+S+W)
ysb.grid(row = 0, column = 1, sticky = N+S)
xsb.grid(row = 1, column = 0, sticky = E+W)
return text
if __name__ == '__main__':
Test().mainloop()
答
您需要配置网格,为行和列赋予非零权重,以便它们展开
You need to configure the grid to give the row and column a nonzero weight so that they expand
from tkinter import *
class Test(Tk):
def __init__(self):
Tk.__init__(self)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.text = frameText(self)
self.geometry('{}x{}'.format(800, 600))
def frameText(frame, **kw):
ysb = Scrollbar(frame)
xsb = Scrollbar(frame, orient = HORIZONTAL)
text = Text(frame, **kw)
ysb.configure(command = text.yview)
xsb.configure(command = text.xview)
text.configure(yscrollcommand = ysb.set, xscrollcommand = xsb.set)
text.grid(row = 0, column = 0, sticky = N+E+S+W)
ysb.grid(row = 0, column = 1, sticky = "ns")
xsb.grid(row = 1, column = 0, sticky = E+W)
return text
if __name__ == '__main__':
Test().mainloop()