【问题标题】:How to make widgets fit in screen如何使小部件适合屏幕
【发布时间】:2015-06-01 14:32:18
【问题描述】:

我无法让我的小部件适合我的计算机屏幕,并且布局未按预期形成。 两个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()

输出:

【问题讨论】:

    标签: python user-interface layout tkinter widget


    【解决方案1】:

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

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

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

    root.grid_rowconfigure(0, weight=1)
    

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

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

    您可以看到InputText 确实没有调整大小,洋红色 request 也没有。 response2Field 占据了整个 绿色 框架(错过了 fill='both' 以进行适当的调整大小处理,但由于部分路径决定了窗口原始大小,所以不可见)。

    【讨论】:

    • 您的语言似乎令人困惑。您可以发布您的代码并逐点解决我的问题吗?
    • 我的回答详细说明了实现目标所需的 3 个步骤:(1) 限制 tk 窗口大小 (2) 在网格中调整大小 (3) 在包中调整大小。我提供 (1) 的代码。对于 (2),您必须为希望看到增长的所有列或行指定权重。对于 (3),您必须在打包 Texts 小部件时添加 fill 参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2020-02-01
    相关资源
    最近更新 更多