如何在python toga中添加带有图标的按钮

问题描述 投票:1回答:1

我正在使用python-toga创建GTK的gui应用,并想知道是否可以创建带有图标的toga.Button()。我尝试使用toga.Command()创建一个命令,该命令可以添加图标,但是无法将命令添加到框中。

这是我的代码中无效的部分:

search_box = toga.Box()
search_box.direction = 'row'
search_box.style.padding = 10
search_box.style.flex = 1

search_label = toga.Label('Search')
search_label.style.padding = (10, 10, 10, 0)

search_input = toga.TextInput(placeholder='Search')
search_input.style.flex = 1
search_input.style.color = "#FFFFFF"

search_command = toga.Command(action=self.test, label='Search') # self.test is a function that just prints user input taken from search_input
search_command.tooltip = 'Search For The Item'
search_command.icon = 'icons/search.png'

search_box.add(search_label)
search_box.add(search_input)
search_box.add(search_command) # This line errors out

运行上面的代码时出现以下错误:

root@host:~/c0balt# briefcase dev

[c0balt] Starting in dev mode...
[GTK+] Not implemented: Widget.set_hidden()
[GTK+] Not implemented: Widget.set_hidden()
[GTK+] Not implemented: Widget.set_hidden()
[GTK+] Not implemented: TextInput.set_font()
[GTK+] Not implemented: Widget.set_hidden()
[GTK+] Not implemented: TextInput.set_font()
[GTK+] Not implemented: TextInput.set_alignment()
[GTK+] Not implemented: TextInput.set_font()
[GTK+] Not implemented: TextInput.set_font()
[GTK+] Not implemented: TextInput.set_font()
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/toga_gtk/app.py", line 91, in gtk_startup
    self.interface.startup()
  File "/root/c0balt/src/c0balt/app.py", line 41, in startup
    search_box.add(search_command)
  File "/usr/local/lib/python3.7/dist-packages/toga/widgets/base.py", line 66, in add
    super().add(child)
  File "/usr/local/lib/python3.7/dist-packages/travertino/node.py", line 80, in add
    set_root(child, self.root)
  File "/usr/local/lib/python3.7/dist-packages/travertino/node.py", line 6, in set_root
    for child in node.children:
AttributeError: 'Command' object has no attribute 'children'

Tl; dr

如何在python-toga中添加具有图标而非纯文本的按钮?

python-3.x user-interface python-3.7
1个回答
0
投票

查看此最小示例(app.py):

import toga
from toga import Group
from toga.style.pack import Pack, COLUMN


def build(app):
    main_box = toga.Box(style=Pack(direction=COLUMN, padding_top=50))
    settings_icon = "icons/example.png"

    toolbar_grp: Group = toga.Group('Toolbar')

    settings_cmd = toga.Command(
        settings_action,
        label='Settings',
        tooltip='Change Settings',
        # shortcut=toga.Key.MOD_1 + 'k',
        icon=settings_icon,
        group=toolbar_grp
    )

    app.commands.add(settings_cmd)
    app.main_window.toolbar.add(settings_cmd)

    return main_box


def settings_action(widget):
    print("Settings")


def main():
    return toga.App('Example', startup=build)


if __name__ == '__main__':
    main().main_loop()

为了运行此示例,您必须在资源文件夹旁边的icons文件夹中放置一个图标,并在其中放置一个名为example.png的文件。

© www.soinside.com 2019 - 2024. All rights reserved.