Кнопка Gtk3 - Уменьшить заполнение внутренней метки - PullRequest
0 голосов
/ 23 апреля 2020

У меня есть кнопка Gtk.But, и я хотел бы уменьшить внутренний левый и правый отступы внутри кнопки, чтобы метка кнопки отображалась с меньшими полями с левой и правой сторон.

Я могу увеличить поля, используя ...

label = button.get_child()
label.set_margin_start(50)
label.set_margin_end(50)

Но я не могу уменьшить поля. Установка полей на ноль не имеет никакого эффекта ...

label = button.get_child()
label.set_margin_start(0)
label.set_margin_end(0)

Я также попытался получить контекст стиля и прочитать свойства полей ...

label = button.get_child()
style_context = label.get_style_context()
margin = style_context.get_margin(Gtk.StateFlags.NORMAL)
print('left   = %s' % margin.left)
print('right  = %s' % margin.right)   
print('top    = %s' % margin.top)   
print('bottom = %s' % margin.bottom)

Но это уже ноль для всех сторон ...

left   = 0
right  = 0
top    = 0
bottom = 0

Как можно уменьшить левый и правый отступ текста внутри кнопки?

РЕДАКТИРОВАТЬ: Я добавил тест код ниже.


basic_window.py

#!/usr/bin/python3

import gi

gi.require_version('Gtk', '3.0')
from gi.repository import GLib
from gi.repository import Gtk

class MainWindowHandlers(Gtk.Window):

    def on_window_destroy(self, *args):

        print('Exit')
        GLib.idle_add(Gtk.main_quit)

    def on_clicked_button_1(self, button):

        print('----------------------------------')
        print('Button 1 Clicked')
        print('----------------------------------')

        # Get the child label.
        label = button.get_child()

        # Set the child's margins to 30. They expand.
        label.set_margin_start(20)
        label.set_margin_end(20)

        # Investigate the child's style context.
        style_context = label.get_style_context()
        margin = style_context.get_margin(Gtk.StateFlags.NORMAL)
        print('left   = %s' % margin.left)
        print('right  = %s' % margin.right)   
        print('top    = %s' % margin.top)   
        print('bottom = %s' % margin.bottom)

        print('----------------------------------')
        print()

    def on_clicked_button_2(self, button):

        print('----------------------------------')
        print('Button 2 Clicked')
        print('----------------------------------')

        # Get the child label.
        label = button.get_child()

        # Set the child's margins to 0.
        # They stay the same size.
        # This does not reduce the left/right padding as I expect.
        label.set_margin_start(0)
        label.set_margin_end(0)

        # Investigate the child's style context.
        style_context = label.get_style_context()
        margin = style_context.get_margin(Gtk.StateFlags.NORMAL)
        print('left   = %s' % margin.left)
        print('right  = %s' % margin.right)   
        print('top    = %s' % margin.top)   
        print('bottom = %s' % margin.bottom)

        print('----------------------------------')
        print()

try:

    builder = Gtk.Builder.new_from_file('basic_window.ui')

    handlers = MainWindowHandlers()
    builder.connect_signals(handlers)

    window = builder.get_object('window')
    window.show()

    Gtk.main()

except Exception as exception:

    print('Error: %s' % exception)

basic_window.ui

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="window">
    <property name="can_focus">False</property>
    <property name="default_width">500</property>
    <property name="default_height">300</property>
    <signal name="destroy" handler="on_window_destroy" swapped="no"/>
    <child>
      <placeholder/>
    </child>
    <child>
      <object class="GtkGrid">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkButton" id="button_2">
            <property name="label" translatable="yes">Add 20 Pixels</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <property name="halign">center</property>
            <property name="valign">center</property>
            <property name="hexpand">True</property>
            <property name="vexpand">True</property>
            <signal name="clicked" handler="on_clicked_button_1" swapped="no"/>
            <style>
              <class name="suggested-action"/>
            </style>
          </object>
          <packing>
            <property name="left_attach">0</property>
            <property name="top_attach">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="button_1">
            <property name="label" translatable="yes">Set to 0 Pixels</property>
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="receives_default">True</property>
            <property name="halign">center</property>
            <property name="valign">center</property>
            <property name="hexpand">True</property>
            <property name="vexpand">True</property>
            <signal name="clicked" handler="on_clicked_button_2" swapped="no"/>
            <style>
              <class name="suggested-action"/>
            </style>
          </object>
          <packing>
            <property name="left_attach">0</property>
            <property name="top_attach">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

1 Ответ

0 голосов
/ 23 апреля 2020

Я уменьшил поле, используя стиль {padding: 0}

Но если есть другая кнопка с большим полем / отступом, то (в моем примере) Box() изменяет размер первой кнопки, чтобы использовать те же размеры. Может потребоваться другой менеджер раскладки

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository import Gdk


class ButtonWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)

        screen = Gdk.Screen.get_default()
        provider = Gtk.CssProvider()
        style_context = Gtk.StyleContext()
        style_context.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        #provider.load_from_path('app.css')
        #provider.load_from_data("#small {margin: 0; padding: 0;}".encode())
        provider.load_from_data("#small {padding: 0;}".encode())

        hbox = Gtk.Box()
        self.add(hbox)

        button1 = Gtk.Button.new_with_label("Padding 0")
        button1.set_name('small') # assign CSS with padding 0
        hbox.pack_start(button1, False, False, 0)

        #button2 = Gtk.Button.new_with_label("Normal padding")
        #hbox.pack_start(button2, True, True, 0)

        #button2.set_name('small') # assign CSS with padding 0

win = ButtonWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

{padding: 0}

enter image description here

Вторая кнопка (со стандартным заполнением) есть выше и автоматически добавляет верхний / нижний отступ к первой кнопке.

enter image description here

Обе кнопки с {padding: 0}

enter image description here

...