
上QQ阅读APP看书,第一时间看更新
2-12 图像PhotoImage
图片可以应用在许多地方,例如标签、功能按钮、选项按钮、文字区域等。在使用前可以用PhotoImage( )方法建立图像对象,然后再将此对象应用在其他窗口组件上。它的语法如下。

需留意PhotoImage( )方法早期只支持gif文件格式,不接受常用的jpg或png格式的图像,目前已经可以支持png格式了。为了使用方便建议将gif图片放在程序所在文件夹中。
可以在Label( )方法内使用“image=imageobj”参数设置此图像对象。
程序实例ch2_19.py:窗口显示html.gif图片的基本应用。

执行结果

如果想要在标签内显示jpg文件,需要借助PIL模块的Image和ImageTk模块,请先导入pillow模块,如下所示。

注意在程序设计中需导入的是PIL模块,主要原因是要向旧版Python Image Library兼容,如下所示。

程序实例ch2_19_1.py:在标签内显示yellowstone.jpg。

执行结果

可以参考2-9节使用compound参数使图像与文字标签共存。
程序实例ch2_20.py:窗口内同时有文字标签和图像的应用。

执行结果

由上图执行结果可以看到,文字标签第2行输出时,是默认的居中对齐。我们可以在Label( )方法内增加justify=LEFT参数,让第2行数据靠左输出。
程序实例ch2_21.py:重新设计ch2_20.py,第10行增加justify=“left”参数让文字标签的第2行数据靠左输出,另外让图像显示在文字标签右边。

执行结果

最后要提醒的是bitmap参数和image参数不能共存,如果发生了这种状况,bitmap参数将不起作用。
程序实例ch2_22.py:图像与文字共存,文字覆盖在图像上方。

执行结果
