Skip to main content
 首页 » 编程设计

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

2025年02月15日7daizhj

我不知道,我怎么能得到这样的结果:

注:文字
多行
更多文字
和更多文字

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

注:文字
多行
更多文字
和更多文字

我试过在 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() 

请您参考如下方法:

现在我明白了你的问题(基于你在下面的评论),这里是如何在 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')