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



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

注:文字
           多行
           一些文字更多
           和更多文本

在该代码中,我得到错误的答案,例如:

注:文字
多行
一些文字更多
和更多文本

在文本换行中,我尝试过,但它破坏了输出文本。

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()

正如我现在理解您的问题(基于您在下面的评论(一样,这是如何在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')

最新更新