单击“保存”按钮后,我试图将第一个输入框中的文本作为新创建的按钮中的文本。但是,我无法获取文本框的输入文本。
我尝试使用entry[0]
来获取文本,但是我不知道文本值是否存储在此位置,它也给我一个错误。该错误显示为“无法解析的引用”。
from tkinter import *
import tkinter as tk
class MainWindow(tk.Frame):
counter = 0
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.button = tk.Button(self, text="Create new hotlink",
command=self.create_window)
self.button.pack(side="top")
def create_window(self):
self.counter += 1
t = tk.Toplevel(self)
t.wm_title("Create New Hotlink")
fields = 'Hotlink Name', 'URL'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width=15, text=field, anchor='w')
ent = Entry(row)
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries.append((field, ent))
return entries
ents = makeform(t, fields)
t.bind('<Return>', (lambda event, e=ents: fetch(e)))
b2 = Button(t, text='Save', command=button2())
b2.pack(side=LEFT, padx=5, pady=5)
def button2():
newButton = tk.Button(root, text=entry[0])
newButton.pack()
if __name__ == "__main__":
root = tk.Tk()
main = MainWindow(root)
main.pack(side="top", fill="both", expand=True)
root.mainloop()
答案 0 :(得分:0)
entry
是局部变量。您不能在那里引用它。您需要认识到ents
变量中存在所有需要的信息。使用它。
我也剥离了代码中不必要的部分。
from tkinter import *
import tkinter as tk
class MainWindow(tk.Frame):
counter = 0
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
self.button = tk.Button(self, text="Create new hotlink", command=self.create_window)
self.button.pack(side="top")
def create_window(self):
self.counter += 1
t = tk.Toplevel(self)
t.wm_title("Create New Hotlink")
fields = 'Hotlink Name', 'URL'
def makeform(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width=15, text=field, anchor='w')
ent = Entry(row)
row.pack(side=TOP, fill=X, padx=5, pady=5)
lab.pack(side=LEFT)
ent.pack(side=RIGHT, expand=YES, fill=X)
entries.append((field, ent))
return entries
def button2():
newButton = tk.Button(root, text=ents[0][1].get())
newButton.pack() #\______________/
ents = makeform(t, fields)
b2 = Button(t, text='Save', command=button2)
b2.pack(side=LEFT, padx=5, pady=5)
if __name__ == "__main__":
root = tk.Tk()
main = MainWindow(root)
main.pack(side="top", fill="both", expand=True)
root.mainloop()