如何从修改后的字符串列表创建 gtk.STOCK_* 按钮?
我正在尝试创建一个简单的程序来显示所有 gtk 库存按钮。
我从以下位置复制了股票 ID 列表:
http://www.pygtk.org/pygtk2tutorial/ch-ButtonWidget.html
将它们粘贴到 .txt 文件中
并从文件创建一个列表:
<代码> stock_file = open('stock_buttons.txt')
stock_button_list = stock_file.readlines()
这会生成一个如下所示的列表:stock_button_list[0] = 'STOCK_DIALOG_INFO/n'
所以我连接了“gtk”。前缀并切掉多余的
然后我用 for 循环创建按钮:
<代码> 对于 stock_button_list 中的每个_button:
self.button1 = gtk.Button(无,each_button)
但是Python 将each_button 解释为字符串,我得到了一堆按钮,其中的stock id 只是标签。 :(
如果我手动创建股票 ID 名称列表,它就会起作用:stock_button_list = [gtk.STOCK_DIALOG_INFO、gtk.STOCK_DIALOG_WARNING 等]
我的列表很好,看起来与股票 ID 相同,但它是一个字符串列表。
如何让 Python 将字符串识别为股票按钮 id 的全局变量?
I'm trying to create a simple program that displays all the gtk stock buttons.
I copied the list of stock id's from:
http://www.pygtk.org/pygtk2tutorial/ch-ButtonWidget.html
pasted them into a .txt file
and created a list from the file:
stock_file = open('stock_buttons.txt')
stock_button_list = stock_file.readlines()
This makes a list which looks like:stock_button_list[0] = ' STOCK_DIALOG_INFO/n'
So I concatenate the 'gtk.' prefix and slice off the excess
Then I create the buttons with a for loop:
for each_button in stock_button_list:
self.button1 = gtk.Button(None, each_button)
But Python interprets each_button as a string and I get a bunch of buttons with the stock ids as just labels. : (
It works if I manually create a list of the stock id names:stock_button_list = [gtk.STOCK_DIALOG_INFO, gtk.STOCK_DIALOG_WARNING, etc.]
My list is fine and looks the same as the stock ids but it is a list of strings.
How can I get Python to recognise strings as the global variables for stock button ids??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如此简单:
使用 getattr 您可以按名称访问对象或模块的所有属性。
So simple:
Using getattr you can access all the attributes of an object or module by name.
一个例子:
An example:
已解决
正如 Revil 所说,使用 getattr(obj,name) 访问带有字符串列表的 gtk.STOCK_* 按钮。
只需确保列表中的每个项目都与对象中的有效名称匹配,否则将引发 AttributeError。
这是我完成的程序。它只是显示所有库存按钮。
*注意:为了使该程序正常工作,您需要在同一目录中创建 stock_buttons.txt。只需将上述问题链接中的股票 ID 列表粘贴到文本文件中即可。
SOLVED
As Revil said, use getattr(obj,name) to access gtk.STOCK_* buttons with a list of strings.
Just make sure that every item in your list matches a valid name in the object, otherwise an AttributeError will be raised.
Here is my finished program. It simply shows all the stock buttons.
*Note: In order for this program to work you need to create stock_buttons.txt in the same dir. Simply paste the list of stock ids from the link in the question above into a text file.