首先,您需要正确缩进代码。函数loop_over_input 中的所有内容都需要比def loop_over_input(the_str=''): 行缩进一次
其他一些注意事项。如果您查找 tkinter 按钮的文档,它将解释如何将命令链接到它。您提供的代码似乎是您希望按钮命令成为的代码。打印列表将在 shell 中完成,而不是在输入字段和按钮下方的框架中。
这里有一些示例代码应该可以满足您的需求:
import tkinter as tk
# Creating tk window
window = tk.Tk()
# Master list
master_list = []
master_list_string = tk.StringVar()
# Frames
top_frame = tk.Frame(window)
top_frame.pack(expand = True, fill = 'x', pady = 10, padx = 10)
bottom_frame = tk.Frame(window)
bottom_frame.pack(expand = True, fill = 'both', padx = 10)
# Entry box
myEntry = tk.Entry(top_frame)
myEntry.pack(side = 'left',expand = True, fill = 'x', padx = 10)
# Label to display master list
myLabel = tk.Label(bottom_frame, textvariable = master_list_string)
myLabel.pack(expand = True, fill = 'both')
# Button to submit
def clicked():
master_list.append(myEntry.get())
myEntry.delete(0, 'end')
printed_list = ''
for password in master_list:
printed_list += "\n" + password
master_list_string.set(printed_list)
myButton = tk.Button(top_frame, text = "Submit", command = clicked)
myButton.pack(side = 'left', padx = 10)
# Mainloop
window.mainloop()
这两个框架允许您在顶部放置条目和按钮,而底部框架用于输出。但是,您不能只使用框架作为输出,因为您的框架不能显示文本。相反,请使用链接到 StringVar 的 Label 小部件,它允许 Label 中的文本在变量更改时更新。
然后按钮命令将输入到条目中的字符串保存到主列表中,然后将StringVar 设置为更新的列表,这会自动更新Label。
我强烈建议准备好关于 Effbot 的文档,通过好的示例很容易理解。链接here