python - 如何更改 GTK 容器小部件的大小?

标签 python gtk3 pygobject gio

我对 Gtk 如何控制容器(例如 GtkBox)内的小部件大小感到非常困惑。请问有人可以指导我解决这个问题的复杂性吗?

我有一个包含两个小部件的 GtkBox - 在示例中它们只是两个 GtkButton。

第一个小部件应该恰好填充 GtkBox 容器内的可用空间。

我想强制第二个小部件始终是一个物理正方形 - 因此,随着正方形的扩大,第一个小部件的宽度将缩小。

一些示例代码将在这里提供帮助:

from gi.repository import Gtk

def on_check_resize(window):
    boxallocation = mainbox.get_allocation()

    width = 0
    height = 0

    if boxallocation.height >= boxallocation.width:
        width = boxallocation.height
        height = width

    if boxallocation.width >= boxallocation.height:
        width = boxallocation.width
        height = width

    secondbtn_allocation = secondbtn.get_allocation()
    secondbtn_allocation.width = width
    secondbtn_allocation.height = height
    secondbtn.set_allocation(secondbtn_allocation)

win = Gtk.Window(title="Containers Demo")
win.set_border_width(10)
win.connect("delete-event", Gtk.main_quit)

mainbox = Gtk.Box()

firstbtn = Gtk.Button(label="just fills the space")
mainbox.pack_start(firstbtn, True, True, 0)
secondbtn = Gtk.Button(label="square")
mainbox.pack_start(secondbtn, False, True, 1)

win.add(mainbox)

win.connect("check_resize", on_check_resize)

win.show_all()

initial = firstbtn.get_allocation()
initial.height = initial.width
firstbtn.set_size_request(initial.width, initial.height)

Gtk.main()

当您展开窗口时 - GtkBox 也会同样展开。那挺好的。第一个按钮同样也会展开。也好。但是,即使我使用 set_allocation,第二个按钮也永远不会是方形的。 GtkWidget 的方法。

我无法使用 set_size_request (或者我可以吗?),因为当我缩小窗口时,由于第二个按钮的最小尺寸已更改,窗口无法调整大小。

我试图弄清楚容器如何管理间距的原因是我希望最终实现像这个 iTunes 示例这样的东西:

enter image description here

即您可以看到封面始终是方形的 - 但音乐细节会根据可用空间缩小或扩大。

最佳答案

使用 Gtk.Grid 代替 Gtk.Box,并设置 hexpandvexpand 属性您打包到网格中的按钮。

此外,请考虑使用 Gtk.AspectFrame对于方形按钮。

关于python - 如何更改 GTK 容器小部件的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23151833/

相关文章:

Python GTK 文件保存对话框,如何创建 "Close Without Saving"ResponseType

python-3.x - 使用 libnotify 的 Python 3 脚本作为 cron 作业失败

localization - 使用 Python/PyGObject 在 Windows 中加载 GTK-Glade 翻译

python - 音频频谱分析仪(15 个条中 4410 个值)

python - 与 Poetry 一起安装的包无法导入

python - GTK3 中的自定义小部件属性

python-3.x - PyGObject. Python 与 GTK。 TreeView 问题

python - 如何更改 GTK 小部件(如堆栈)的属性?

python - 用户按下所有答案后如何在 python 中结束循环?

python - 使用flask、pythonanywhere显示字典中的数据