我的目标是使用for循环创建10个下拉列表(我希望以后可以访问这些值),以分配每个StringVar()和tk.OptionMenu()。但是,我收到 AttributeError:
'str'对象没有属性'set'
尽管我的变量分配了一个tkinter.StringVar对象:
{'self.comp0': <tkinter.StringVar object at 0x046B9890>, 'self.comp1': <tkinter.StringVar object at 0x0C5E19B0>
代码:
from tkinter import OptionMenu
import tkinter as Tkinter
import tkinter.filedialog as tkFileDialog
from tkinter import messagebox as tkMessageBox
class GasGen(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
self.grid()
def initialize(self):
vars= {}
for i in range(8):
name = "self.comp" + str(i)
vars[name] = Tkinter.StringVar()
menus = {}
for num, i in enumerate(vars):
names = "menu" + str(num)
menus[name] = OptionMenu(self, i, "methane", "ethane", "propane", "iso-butane", "n-butane", "iso-pentane", "n-pentane", "benzene").grid(column = 0, row = num)
print(vars)
print(".......................")
print(menus)
if __name__ == "__main__":
app = GasGen(None)
app.title('Gas mixture generator')
app.configure(background = "slate gray")
app.mainloop()
退出:
{'self.comp0': <tkinter.StringVar object at 0x03EA3670>, 'self.comp1': <tkinter.StringVar object at 0x0BB919B0>, 'self.comp2': <tkinter.StringVar object at 0x05045690>, 'self.comp3': <tkinter.StringVar object at 0x0BBE59B0>, 'self.comp4': <tkinter.StringVar object at 0x0BBE5CB0>, 'self.comp5': <tkinter.StringVar object at 0x0BBF54B0>, 'self.comp6': <tkinter.StringVar object at 0x0BBF54F0>, 'self.comp7': <tkinter.StringVar object at 0x0BBF5530>}
..........................
> {'menu0': None, 'menu1': None, 'menu2': None, 'menu3': None, 'menu4':
> None, 'menu5': None, 'menu6': None, 'menu7': None}
这不是在tkinter中分配变量的好方法吗?如果不是,是否有更好的方法来动态生成这些变量,以允许我在tkinter应用程序中将值设置为其名称?