如何使小部件适合屏幕

时间:2015-03-28 07:08:33

标签: python user-interface layout tkinter widget

我不能让我的小部件适合我的电脑屏幕,并且布局没有按预期形成。 两个Text小部件应该展开并占据其可用的框架的剩余部分,包含response2Field的第二个框架应该适合屏幕,但它不会发生。 我怎样才能实现这些目标?

# -*- coding: utf-8 -*-
from Tkinter import Tk,Label,Entry,Text,Button,Frame

text = """Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others."""
root = Tk() 
request = Frame(root)
response =  Frame(root)
response1 = Frame(response)
response2 = Frame(response)
request.grid(row=0,column=0,sticky='news')
response.grid(row=0,column=1)
response1.grid(row=0,column=0,sticky='w')
response2.grid(row=1,column=0,sticky='news')

InputText = Text(request)
InputText.pack(expand='true')
Button(response1,text='Submit',bg='brown',fg='yellow').pack()
response2Field = Text(response2,bg='black',fg='green')
response2Field.pack(expand='true')
InputText.insert("1.0",text)
response2Field.insert("1.0",text)
root.mainloop()

输出: Result

1 个答案:

答案 0 :(得分:2)

tkinter几何管理器包和网格的默认行为是增加容器和窗口以显示放在其中的所有内容。如果你想限制这个,你可以在gui建筑代码的末尾添加(从this other answer复制)

root.geometry('{}x{}'.format(<widthpixels>, <heightpixels>))

要使其正常工作,您必须在布局中正确调整大小。首先,您对网格的使用过于复杂,您不必使用所有这些中间框架,并且可以将您的小部件直接放在网格中。其次,需要指示网格应该增长哪些行和列。这是通过weight参数完成的。它描述了元素的增长率(相对于同一级别的所有权重之和),默认为0.这是在容器端配置的。例如,要让requestresponse填满整个窗口高度,您必须添加

root.grid_rowconfigure(0, weight=1)

在打包方面,您必须同时指定参数展开和填充,以使小部件填充整个可用空间pack(expand='true', fill='both')

要想象您的Frame容器的重新调整大小的行为,您可以考虑添加边框borderwidth=2, relief='sunken'或背景background='magenta'(它会伤害眼睛,但有助于理解)。

same program with relief and colored frame

您可以看到确实InputText没有调整大小, magenta requestresponse2Field占据了整个绿色框架(错过了填充=&#39;两者&#39;用于正确的调整大小处理,但由于确定窗口原始大小的部分路径不可见)。< / p>

相关问题