我正在尝试使用组合框,2个按钮和文本框小部件的组合来显示* .txt文件中的文本。但我的代码有问题。我无法继续前进,需要帮助。请参阅下面的代码。
f3 = Frame(page2, bg="purple", width="800", height="2")
f3.pack(side=TOP)
f4 = Frame(page2, bg="purple", width="800", height="60")
f4.pack(side=BOTTOM)
arr = []
combo = ttk.Combobox(f3, height="10", width="69")
combo.pack(side=LEFT)
def load():
tid = tb2.get("1.0", END).replace('\n', '').replace("Destination
Folder :", '')
arr = [x for x in os.listdir(tid) if x.endswith(".txt")]
for i in arr:
combo.insert('end', i)
def display():
tb3.delete(1.0, END)
if len(tb2.get("1.0", END)) > 2:
tid = tb2.get("1.0", END).replace('\n', '').replace("Destination
Folder :", '')
file = combo.get()
selected = os.path.join(tid, file)
with open(selected) as textfile:
tb3.insert('end', textfile.read())
else:
messagebox.showinfo(title="PROCEDURAL ERROR", message="FOLDER is
not set. \nSet Destination")
pbtn7 = Button(f3, text="LOAD", activebackground="magenta",
activeforeground="white", bd="5", bg="powder blue",
command=load, fg="purple", font=('arial', 10, 'bold'))
pbtn7.pack(side=LEFT)
pbtn6 = Button(f3, text="DISPLAY", activebackground="magenta",
activeforeground="white", bd="5", bg="powder blue",
command=display, fg="purple", font=('arial', 10, 'bold'))
pbtn6.pack(side=RIGHT)
tb3 = Text(f4, height="40", width="100")
tb3.pack()
#========================================
root.mainloop()
整个想法是获取一个字符串形式的路径,该路径被修改并存储在变量“tid”中,然后该路径用于浏览要在组合框中列出的文件夹中的所有文本文件。然后显示按钮用于显示所选文件的文本
答案 0 :(得分:1)
您不需要循环来加载组合框。您可以将列表指定为值:
combo['values'] = arr
然后您可以通过以下方式显示它:
def display():
with open(combo.get()) as textfile:
tb3.insert('end', textfile.read())
你真的应该阅读文档。这并不难:)