Python tkinter文本小部件使​​用网格填充固定大小的框架

时间:2016-04-02 21:05:51

标签: python tkinter

在Raspberry Pi上运行Python 3.4.2和Tkinter 8.6。我想创建一个Text小部件,使用网格布局管理器填充固定大小的框架。

如果您运行下面的代码,您将看到文本窗口小部件未填充800x600帧。我意识到我可以设置文本的宽度和高度属性来填充框架,但这只能使用默认字体,并且不会完全填充框架。

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

1 个答案:

答案 0 :(得分:1)

您需要配置网格以使行和列具有非零权重,以便它们展开

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