python 如何按行读文件并逐行显示在lixtbox中 现实到别的场景也行 只要能显示在ui上就好? 急求……………
# encoding: UTF-8
# _*_ coding:utf-8 _*_
from Tkinter import *
from SimpleDialog import *
import thread
import sys,time
class PPChatClitGUI(object):
def __init__(self):
self.top=Tk()
self.top.title('Display lrc')
self.frame=[]
self.frame.append(Frame())
self.frame.append(Frame())
self.MessageIn=Entry(self.frame[0],width=60,fg='red')
self.MessageIn.pack(fill=X,expand=1,pady=10,padx=15)
self.sendMesgButton=Button(self.frame[0],
text='OK',
width=10,
command=self.Show)
self.sendMesgButton.pack(side=BOTTOM and RIGHT,
padx=20,
pady=10)
self.quitButton=Button(self.frame[0],
text='Quit',
width=10,
command=self.OnQuit)
self.quitButton.pack(side=RIGHT,padx=20,pady=10)
self.frame[0].pack()
self.slbar=Scrollbar(self.frame[1])
self.slbar.pack(side=RIGHT,fill=Y)
self.MessageOut=Listbox(self.frame[1],height=25)
self.MessageOut['yscrollcommand']=self.slbar.set
self.MessageOut.pack(expand=1,fill=BOTH)
self.slbar['command']=self.MessageOut.yview
self.frame[1].pack(expand=1,fill=BOTH)
def Show(self):
tam=self.MessageIn.get()
self.Lrc(tam)
def Lrc(self,tam):
file = open(str(tam))
while 1:
line = file.readline()
self.MessageOut.insert(END,str(line[10:100]))
print line
time.sleep(1)
if not line:
break
file.close()
def OnQuit(self):
self.top.quit()
def main():
pp=PPChatClitGUI()
mainloop()
if __name__=='__main__':
main()
[解决办法]
gui线程里的回调函数要尽快办完事,你用while+sleep方式不好,阻塞了看不到正常的更新动作,tk的控件有个after方法,试试类似下面方式改写一下Show函数:
def Show(self, f=None): if not f: tam=self.MessageIn.get() f = open(tam) line = f.readline() if not line: f.close() return self.MessageOut.insert(END, line[10:100]) print line self.top.after(1000, self.Show, f)