Python - 从文件到Tkinter文本逐行读取

时间:2016-08-30 09:55:36

标签: python python-2.7 tkinter textbox

我决定要用Python Tkinter进行一些GUI编程,我想从文本编辑器开始。我已经编写了一些代码,一切看起来都很好但是我在将文本插入Text小部件时遇到了麻烦。它不会插入所有行只是一个。任何人似乎都知道答案?我从Tkinter开始,我可能会转向PyQT。我想使用Python 2.7,所以请不要发布Python 3.x asnwers。感谢

import Tkinter as TK
from tkFileDialog import *

#Callbacks
def clearCallback(event):
    print "Clearing..."
    textBox.delete("1.0",TK.END)
    print "Cleared."
return
def openCallback(event):
    print "Trying to open a file..."
    fname = askopenfile(mode='r',initialdir="C:\\")
    if(fname):
        print str(fname)
        content = fname.readlines()
        print str(content)
        for line in content:
            textBox.insert(TK.END,line)
        fname.close()
        return
    else:
        print "No file was opened."
    return
print "---MiniPyE---"
#Base
base = TK.Tk()
base.resizable(height=False,width=False)
base.minsize(650,600)
base.title("MiniPyE")
#Buttons
#Clear Button
clearButton = TK.Button(base,text="New")
clearButton.place(x=16,y=0,height=16,width=48)
clearButton.bind("<Button-1>",clearCallback)
#Open Button
openButton = TK.Button(base,text="Open")
openButton.place(x=16+48,y=0,height=16,width=48)
openButton.bind("<Button-1>",openCallback)
#Text Box
textBox = TK.Text()
textBox.place(x=16,y=16,height = 684,width=650)
#Scrollbar
scrollBar = TK.Scrollbar(base,command=textBox.yview)
scrollBar.place(x=0,y=0,height=584)
#scrollBar.grid(row=0,column=1,sticky='nsew')
base.mainloop()

1 个答案:

答案 0 :(得分:0)

我修好了。事情是高度太大了。我改变了:
textBox.place(x=16,y=16,height=684,width=650)

textBox.place(x=16,y=16,height=580)
一切都很顺利。正如预期的那样。