我正在开发一个 wxPython GUI,并且想要右对齐快捷方式文本。显然,人们可以使用制表符来解决这个问题,但如果有办法的话,我更愿意在本地执行此操作。
默认的菜单项创建如下:
menu = wx.Menu()
item_id = 1
item_name = 'My menu item'
help_text = 'Clicking this does something interesting.'
item = menu.Append(item_id, item_name, help_text)
我将使用快捷方式对此进行扩展,因此如果我使用选项卡,它将类似于:
item_name = 'My menu item\t\tCtrl+Alt+H'
但是,这涉及大量手动 \t
条目,以确保所有内容都对齐,并且每当菜单项更改名称或添加另一个项目时,它们都可能需要更新。有没有办法解决这个问题,例如我没有看到自动将键绑定(bind)与菜单项关联的类方法?
编辑:我知道,当传递像 &My menu item
这样的文本时,它会使用与指定的 ID 关联的键绑定(bind)自动执行一些操作,如果加速器表中有一个与该 ID 关联的定义,对吗?
最佳答案
我深入研究了其他几个应用程序的代码来寻找答案。事实证明,默认行为是 \t
并没有像它看起来那样做(即插入制表符),但工具包明智地将其解释为正是我想做的事情。因此,右对齐快捷方式的方法很简单:使用所需的文本创建它,然后添加 \t<shortcut>
(就像我上面那样)。在我上面粘贴的示例代码中,如果我希望快捷方式为 Ctrl + T
,因此应该是这样:
menu = wx.Menu()
item_id = 1
item_name = 'My menu item\tCtrl+T'
help_text = 'Clicking this does something interesting.'
item = menu.Append(item_id, item_name, help_text)
编辑:根据 Mike Driscoll 的 very helpful answer 更新了以下部分.
请注意,这会创建快捷方式绑定(bind)(wxPython 选择它),但它不会使其可以使用例如Windows 上的 Alt 键。
您可以关联 Alt 键以快速打开菜单并使用 item_name
中的 & 符号导航到该菜单。文本,但您仍然需要通过 AcceleratorTable
手动关联所需的键绑定(bind):
menu = wx.Menu()
item_id = 1
# Ctrl+T is bound to the keybinding
accelerator_table = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('T'), item_id)])
self.setAcceleratorTable(accelerator_table)
# Ctrl+T is not included, but the menu item can be accessed via Alt key
item_name = '&My menu item'
help_text = 'Clicking this does something interesting.'
item = menu.Append(item_id, item_name, help_text)
我想,这实际上是首选模式,就像 item_id
的任何地方一样。被引用后,可以自动引用该快捷方式。这也将有助于无缝更新。
关于python - wxPython菜单文本对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15552209/