这里是python 3.4,程序导入tkinter模块来构建gui接口。
我想知道如何制作一个能够添加新字段供用户填写的按钮
尝试应用内置方法 vars()和 getattr(),但它不起作用。
我无法弄清楚为什么总会弹出 AttributeError 。
以下是我的代码的一部分:
import tkinter as Tk
from tkinter import ttk
class dictionary(Tk.Frame):
def __init__(self, master=None):
Tk.Frame.__init__(self, master)
#......other line here........
def createWidgets(self):
self.row_c = 0
self.new_0 = Tk.StringVar(self)
self.new_0field = ttk.Entry(self, textvariable=self.new_0)
self.new_0field.grid(row=self.row_c, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
self.add_lang = ttk.Button(self, text="add language", command=self.add_field)
self.add_lang.bind("<Return>", self.add_field)
self.add_lang.grid(row=self.row_c, column=3, padx=4, pady=6, sticky="W")
self.row_c += 1
def add_field(self):
#count is a number (string type)
count = str(self.row_c)
vars()["self.new_" + count] = Tk.StringVar(self)
vars()["self.new_" + count + "field"] = ttk.Entry(self, textvariable=getattr(self, "self.new_"+count))
vars()["self.new_" + count + "field"].grid(row=self.row_c+1, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
self.add_lang.grid(row=self.row_c+1, column=3, padx=4, pady=6, sticky="W")
if __name__ == '__main__':
root = Tk.Tk()
app = dictionary(master=root)
app.mainloop()
是否可以通过tkinter中的按钮添加字段?
如果有任何建议让它发挥作用,我将不胜感激
谢谢!
答案 0 :(得分:1)
所以这是我的解决方案:
import tkinter as tk
from tkinter import ttk
class dictionary(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.fields = []
self.createWidgets()
self.grid(column=0, sticky="NEWS")
def createWidgets(self):
self.add_field()
self.add_lang = ttk.Button(self, text="add language", command=self.add_field)
self.add_lang.bind("<Return>", self.add_field)
self.add_lang.grid(row=len(self.fields), column=3, padx=4, pady=6, sticky="W")
def add_field(self):
self.fields.append({})
n = len(self.fields)-1
self.fields[n]['var'] = tk.StringVar(self)
self.fields[n]['field'] = ttk.Entry(self, textvariable=self.fields[n]['var'])
self.fields[n]['field'].grid(row=n, column=0, columnspan=2, padx=4, pady=6, sticky="NEWS")
if n:
self.add_lang.grid(row=n + 1, column=3, padx=4, pady=6, sticky="W")
if __name__ == '__main__':
root = tk.Tk()
app = dictionary(master=root)
app.mainloop()
我希望这就是你想要的。