【问题标题】:Python GTK3: button with image and label and get the Label value after click eventPython GTK3:带有图像和标签的按钮并在单击事件后获取标签值
【发布时间】:2020-10-14 16:14:15
【问题描述】:

我正在尝试获取网格内的标签值,并且该网格在单击事件后位于按钮内。

这是我的部分代码:

for one_text in text_list:
    label_for_button = Gtk.Label(one_text)
    label_for_button.set_line_wrap(True)
    image_for_button = Gtk.Image.new_from_file("img.png")
    grid_in_button = Gtk.Grid()
    grid_in_button.add(image_button)
    grid_in_button.attach_next_to(label_for_button, image_for_button, Gtk.PositionType.BOTTOM, 1, 2)
    grid_in_button.show_all()
    button.add(grid_in_button)

    button.connect("clicked", self.on_button_clicked)

def on_button_clicked(self, widget):
    # here i wanna get the value of the label_for_button

帮助.. 有什么想法吗?谢谢

【问题讨论】:

  • 函数的第二个参数包含有关按钮的信息。在函数on_button_clickprint(widget.get_label()),看看是否有效
  • 我已经完成了,但它返回“无”。可能是因为它包含按钮、网格和标签在网格内。
  • 解决方法是:widget.get_child().get_child_at(0, 1).get_label()

标签: python python-3.x gtk3


【解决方案1】:

希望这段代码有帮助:

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

def btn_clicked(widget):
    print(widget.get_label())

pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename="img.png", width=24, height=24, preserve_aspect_ratio=True)
img = Gtk.Image.new_from_pixbuf(pixbuf)
btn = Gtk.Button(label='some text',image=img,)
btn.connect('clicked',btn_clicked)
win = Gtk.Window()
win.connect("destroy", Gtk.main_quit)
win.add(btn)
win.show_all()
Gtk.main()

【讨论】:

  • 谢谢!它可以工作,但您需要添加 btn.set_always_show_image(True) 以便它可以显示图像。对于我制作的代码,我找到了解决方案:widget.get_child().get_child_at(0, 1).get_label() widget 是按钮。 .get_child() 获取网格。 .get_child_at(0, 1) 获取该位置的标签。 .get_label() 从中获取文本。
猜你喜欢
  • 2014-08-30
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多