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

标签 python python-3.x tkinter textbox word-wrap

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

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

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

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

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

关于python - 如何在多行前添加制表符或空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44638233/

相关文章:

Python:在for循环中向迭代变量添加常量

python - 在 wxPython 中调整父级大小时重新缩放图像

python - 根据另一列中的组和条件填充列

python - ubuntu 16.4 上的 tkinter 导入错误

python - 全局变量没有传递,说它不被识别?

python - 在字典 switch 语句中模拟 'else'

python - 如何使用正则表达式限制Python中的子字符串大小

python - 导入前 PyCharm 打印?

mysql - 使用 Python 在 MySQL 数据库上进行实时搜索

python - 在 python 中显示更新的文本文件