已解决
正如 Revil 所说,使用 getattr(obj,name) 访问带有字符串列表的 gtk.STOCK_* 按钮。
只需确保列表中的每个项目都与对象中的有效名称匹配,否则将引发 AttributeError。
这是我完成的程序。它只是显示所有股票按钮。
*注意:为了让这个程序工作,你需要在同一个目录中创建 stock_buttons.txt。只需将上述问题中链接中的股票 ID 列表粘贴到文本文件中即可。
#!/usr/bin/env python
# stock_buttons.py
# Simple program to show all stock buttons
# Author: oringe
import pygtk
pygtk.require('2.0')
import gtk
class stock_buttons:
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title("gtk.STOCK_[Buttons]")
self.window.connect("destroy", lambda wid: gtk.main_quit())
self.window.connect("delete_event", lambda a1,a2:gtk.main_quit())
self.window.set_border_width(10)
# This horizontal box will contain the columns
self.boxH = gtk.HBox(False, 0)
self.window.add(self.boxH)
# Pack the five columns into the HBox
self.box1 = gtk.VBox(False, 0)
self.boxH.pack_start(self.box1, True, True, 0)
self.box2 = gtk.VBox(False, 0)
self.boxH.pack_start(self.box2, True, True, 0)
self.box3 = gtk.VBox(False, 0)
self.boxH.pack_start(self.box3, True, True, 0)
self.box4 = gtk.VBox(False, 0)
self.boxH.pack_start(self.box4, True, True, 0)
self.box5 = gtk.VBox(False, 0)
self.boxH.pack_start(self.box5, True, True, 0)
# Make the list of stock buttons
stock_file = open('stock_buttons.txt')
stock_button_list = stock_file.readlines()
# Slice off excess spaces and line breaks
i = 0
for each_string in stock_button_list:
stock_button_list[i] = stock_button_list[i][2:-1]
i += 1
# Pack 15 buttons per column
i2 = 0
for button in stock_button_list:
if i2 < 15:
self.button1 = gtk.Button(stock=getattr(gtk, button))
self.box1.pack_start(self.button1, True, True, 0)
self.button1.show()
i2 += 1
elif i2 > 14 and i2 < 30:
self.button1 = gtk.Button(stock=getattr(gtk, button))
self.box2.pack_start(self.button1, True, True, 0)
self.button1.show()
i2 += 1
elif i2 > 29 and i2 < 45:
self.button1 = gtk.Button(stock=getattr(gtk, button))
self.box3.pack_start(self.button1, True, True, 0)
self.button1.show()
i2 += 1
elif i2 > 44 and i2 < 60:
self.button1 = gtk.Button(stock=getattr(gtk, button))
self.box4.pack_start(self.button1, True, True, 0)
self.button1.show()
i2 += 1
elif i2 > 59 and i2 < 75 and button != '': #Last item in list is empty''
self.button1 = gtk.Button(stock=getattr(gtk, button))
self.box5.pack_start(self.button1, True, True, 0)
self.button1.show()
i2 += 1
self.box1.show()
self.box2.show()
self.box3.show()
self.box4.show()
self.box5.show()
self.boxH.show()
self.window.show()
def main():
gtk.main()
if __name__ == "__main__":
mybuttons = stock_buttons()
main()