我无法将我的一个文本文件加载到GUI中。我有一个加载函数(在菜单栏上),并创建了一个列表框。
加载菜单和列表框的代码:
class View(Listbox):
def __init__(self, master):
Listbox.__init__(self, master) #makes view class listbox
class Controller(object):
def __init__(self, master):
""" Main interface:
master - the top level window
"""
self._master = master
menubar = Menu(self._master)
frame1 = Frame(self._master)
frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)
self._Listbox=View(frame1)
self._Listbox.pack(side = TOP,fill=BOTH, expand = True,pady=20)
menubar = Menu(self._master)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open rooms file", command = self.file_open)
def file_open(self):
filename = tkFileDialog.askopenfilename()
加载文件有效,但当前加载的文本文档在哪里?如何在列表框中显示它?
答案 0 :(得分:3)
这有效:
from Tkinter import *
import tkFileDialog
class View(Listbox):
def __init__(self, master):
Listbox.__init__(self, master) #makes view class listbox
class Controller(object):
def __init__(self, master):
""" Main interface:
master - the top level window
"""
self._master = master
frame1 = Frame(self._master)
frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)
self._Listbox=View(frame1)
self._Listbox.pack(side = TOP,fill=BOTH, expand = True,pady=20)
menubar = Menu(self._master)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command = self.file_open)
menubar.add_cascade(label='File',menu=filemenu)
self._master.config(menu=menubar)
def file_open(self):
filename = tkFileDialog.askopenfilename()
#insert each line in the file into the listbox
with open(filename,'r') as f:
for line in f:
self._Listbox.insert(END,line)
if __name__ == "__main__":
root=Tk()
c=Controller(root)
root.mainloop()
这只与你的代码略有不同......首先,我删除了第一个menubar = Menu(self._master)
,因为它没有真正做任何事情。其次,我添加了“级联”menubar.add_cascade(label='File',menu=filemenu)
,第三,我实际将菜单附加到根Tk
窗口:self._master.config(menu=menubar)