如何在多行前面添加制表符或空格

时间:2017-06-19 19:14:02

标签: python python-3.x tkinter textbox textwrapping

我无法弄明白,我怎么能得到这样的结果:

注意:文字
多行
一些文字更多
更多文字

在那段代码中我得到了错误的答案,如:

注意:文字
多行
一些文字更多
更多文字

在textwrap中我试过但它破坏了输出文本。

import tkinter as tk

# make file
try:  
    open('MyPyDict.txt')
except FileNotFoundError:
    open('MyPyDict.txt', 'w')


# button for text input
def insert():  
    note = entry_note.get()
    text = entry_defs.get('1.0', 'end-1c')
    print(note + ' : ' + text + '\n')
    # f = open('MyPyDict.txt', 'a', encoding='utf-8')
    # f.write(note + ' : ' + text + '\n')

master = tk.Tk()  # program window
master.title('MyPyDict')
master.geometry('400x350')

# note label
label_note = tk.Label(master, text='Note', font=16)
label_note.place(x=5, y=20)

# Insert/Search label
label_text = tk.Label(master, text='Insert/Search', font=16)
label_text.place(x=5, y=55)

# for inserting and searching textbox
entry_defs = tk.Text(master, font=16, height=10, width=20)
entry_defs.place(x=120, y=55)

# note entry
entry_note = tk.Entry(master, font=16)
entry_note.place(x=120, y=20)

# insert button
button_insert = tk.Button(master, text='Insert', font=16, command=insert)
button_insert.place(x=252, y=250)

# search button
button_search = tk.Button(master, text='Search', font=16)
button_search.place(x=180, y=250)

master.mainloop()

1 个答案:

答案 0 :(得分:1)

我现在理解你的问题(基于你在下面的评论),这是在textwrap模块的帮助下如何完成的。

请注意,这不会将制表符放在行前面,而是放置一个由空格字符组成的前缀字符串,以便它们排成一行。如果您真的想要制表符,请设置prefix = '\t'而不是显示的内容。

import textwrap

# button for text input
def insert():
    note = entry_note.get() + ' : '
    text = note + entry_defs.get('1.0', 'end-1c')
    textlines = text.splitlines(True)
    prefix = ' ' * len(note)
    formatted = textlines[0] + textwrap.indent(''.join(textlines[1:]), prefix)
    print(formatted)
    # f = open('MyPyDict.txt', 'a', encoding='utf-8')
    # f.write(formatted + '\n')