对于此程序,需要根据用户输入选择不同的类。简而言之,该计划如何运作:
OnButtonAddNew
,形状会添加到element
由于所有形状都需要相同数量的变量(或者我让一些var为空),因此应该可以使用变量将新元素添加到元素列表中。我现在用self.x
尝试它的方式并没有成功。我也尝试使用getattr
,但这对我来说也没有用。
import tkinter as tk
element = [] # stores list of objects
class mainWindow(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
'Input of values'
tk.Label(self, text='y').grid(column=2, row=16, sticky=tk.W)
self.y = tk.DoubleVar()
self.entryY = tk.Entry(self, textvariable=self.y)
self.entryY.grid(column=3, row=16, sticky='EW')
'Drowdown menu'
self.options = ['Square', 'Triangle'] # multiple types of classes
self.var = tk.StringVar()
self.var.set(self.options[0])
self.DropDown = tk.OptionMenu(self, self.var, *self.options, command=self.initForm)
self.DropDown.grid(column=3, row=5)
'Button add new object'
self.buttonSet = tk.Button(self, text='Set', width=12, command=self.OnButtonAddNewClick)
self.buttonSet.grid(column=2, row=30)
self.update()
def initForm(self, event):
self.x = self.var.get() # get selected type of class
def OnButtonAddNewClick(self):
global element
new_element = self.x(self.y.get(), len(element)) # create new instance of class and add it to the elements
element = np.append(element, new_element)
class Square:
def __init__(self, y0, elementNumber):
self.y0 = y0
print('Added new instance square, y0:', self.y0)
class Triangle:
def __init__(self, y0, elementNumber):
self.y0 = y0
print('Added new instance triangle, y0:', self.y0)
if __name__ == '__main__':
root = tk.Tk()
mainWindow(root).pack(side='top', fill='both')
root.mainloop()
提前致谢。
答案 0 :(得分:0)
执行此操作的可能方法是使用globals()
:
class C:
def __init__(self, x):
self.x = x
print('Added new instance square, y0:', self.x)
def call(str):
obj = globals()[str](4)
return obj
c = call('C')
print(c.x)