# encoding: utf-8 import time from Tkinter import * def write(file1,file2): with open(file1) as f1: for line in f1: f2 = open(file2, 'a+') f2.write(line) time.sleep(0.00001) def read(file2): with open(file2) as f: all_part = [] for line in f: line = line.strip() all_part.append(line) return all_part def windows1(file2): root = Tk() root.title("serial log") s1 = Scrollbar(root) s1.pack(side=RIGHT, fill=Y) s2 = Scrollbar(root, orient=HORIZONTAL) s2.pack(side=BOTTOM, fill=X) textpad = Text(root, yscrollcommand=s1.set, xscrollcommand=s2.set, wrap='none') textpad.pack(expand=YES, fill=BOTH) s1.config(command=textpad.yview) s2.config(command=textpad.xview) with open(file2) as f: #這里用while沒有用for,是因為文件較大,用for會hang。壞處是窗口不會自動關閉。自動關閉會報錯,錯誤如下: # C:\Users\yuxinglx\Downloads\test\venv\Scripts\python.exe C:/Users/yuxinglx/Downloads/test/2018-07-16/1.py # Traceback (most recent call last): # File "C:/Users/yuxinglx/Downloads/test/2018-07-16/1.py", line 67, in <module> # read(file2) # File "C:/Users/yuxinglx/Downloads/test/2018-07-16/1.py", line 27, in read # textpad.pack() # File "C:\Python27\Lib\lib-tk\Tkinter.py", line 1936, in pack_configure # + self._options(cnf, kw)) # _tkinter.TclError: can't invoke "pack" command: application has been destroyed # # Process finished with exit code 1 while True: line = f.readline() textpad.pack() textpad.insert(END, line) #窗口顯示最后一行,頁面會自動滾動。壞處是Y軸滾動條一直在最下方不會向上。 #不加textpad.see(END)這行,Y軸滾動條可以上下滑動,但是壞處是頁面不會自動滾動。 # textpad.see(END) root.update() #只添加Y軸滾動條,用for讀取小文件,大文件會hang。並且只用for,循環完窗口會主動關閉。 def windows2(all_part): root = Tk() root.title("serial log") scroll = Scrollbar() text = Text(root) scroll.pack(side=RIGHT, fill=Y) text.pack(side=LEFT, fill=Y) scroll.config(command=text.yview) text.config(yscrollcommand=scroll.set) while True: for i in all_part: text.pack() text.insert(END, i) root.update() # time.sleep(0.0003) if __name__ == '__main__': file1 = 'log.txt' file2 = 'result.txt' read(file2) # windows1(file2) # windows2(read(file2)) # write(file1, file2)
以上代碼在python2.7.9上通過運行。