我正在用tkinter做抵押计算器。我尝试从一个单独的文件动态创建小部件,该文件包含具有相关属性的列表。你知道吗
主文件是:
import tkinter as tk
import tkinter.ttk as ttk
import tkinterwidgetinfo as twi
root=tk.Tk()
root.title('Tkinter Practice')
class Application(ttk.Frame):
def __init__(self, master=None):
super().__init__()
self.pack()
self.createApplication()
def createApplication(self):
## create widgets dynamically from twi
for i in twi.progWidgets:
a = i[1]+i[2]+'**'+str(i[3])+')'
i[0] = eval(a)
i[0].pack()
app = Application(root)
app.mainloop()
包含小部件信息的列表在一个单独的文件中并导入。信息如下:
progWidgets = [
['inputFrame', 'ttk.LabelFrame(', '', {'text': "User Input",
'labelanchor': "nw"}],
['principalLabel', 'ttk.Label(', 'inputFrame,', {'text' : "Principal(£)"}],
['principalEntry', 'ttk.Entry(', 'inputFrame,', {}],
['termLabel', 'ttk.Label(', 'inputFrame,', {'text' : "Mortgage Term (Years)"}],
['termEntry', 'ttk.Entry(', 'inputFrame,', {}]
]
当我运行这个代码时,第一个小部件(labelframe)并没有被创建。但是,当我在循环外创建labelframe时,如下所示:
import tkinter as tk
import tkinter.ttk as ttk
import tkinterwidgetinfo as twi
root=tk.Tk()
root.title('Tkinter Practice')
class Application(ttk.Frame):
def __init__(self, master=None):
super().__init__()
self.pack()
self.createApplication()
def createApplication(self):
inputFrame = ttk.Labelframe(text = "User Input",
labelanchor = "nw")
inputFrame.pack()
## create widgets dynamically from twi
for i in twi.progWidgets:
a = i[1]+i[2]+'**'+str(i[3])+')'
i[0] = eval(a)
i[0].pack()
app = Application(root)
app.mainloop()
程序运行良好。如何在循环中包含labelframe?你知道吗
使用
'inputFrame'
作为父名称,但未定义。当您运行第二段代码时,定义了inputFrame
,一切正常。你知道吗我同意评论者的看法,使用
eval
是一个糟糕的想法(安全原因、灵活性),但您仍然可以这样做:相关问题 更多 >
编程相关推荐