python为text添加滚动条_python Tkinter的Text组件中创建x轴和y轴滚动条,并且text文本框自动更新(一)...

本文介绍了如何使用Python编写函数,实现在文件读取、写入操作后更新显示,并展示两种不同窗口实现方式:windows1通过逐行读取大文件并实时滚动,适用于处理大型文件;windows2则一次性加载所有内容到文本框中,适合小文件或一次性展示。
摘要由CSDN通过智能技术生成

# 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

# 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上通过运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值