有没有办法在Tkinter文本小部件上设置换行长度



问题

我正在尝试用Tkinter做一个文本编辑器。如果打开了一个大的单行文件,它会严重滞后并停止响应。有没有办法为文本小部件设置换行长度?我有滚动条,我不想让字符在文本框的末尾换行。我希望它在一定数量的字符后换行。

这可能吗?如果是,我该怎么做?

我在64位Windows 10上使用Python 3.9.6。

我尝试过的

我试过在函数中使用wrappelength=,但不起作用。我也搜索过这个问题,但一无所获。

代码

from tkinter import *
root = Tk()
root.title('Notpad [new file]')
root.geometry('1225x720')

txt = Text(root,width=150,height=40,wrap=NONE)
txt.place(x=0,y=0)
#Buttons here

scr = Scrollbar(root)
scr.pack(side='right',fill='y',expand=False)
txt.config(yscrollcommand=scr.set)
scr.config(command=txt.yview)
scr1 = Scrollbar(root,orient='horizontal')
scr1.pack(side='bottom',fill='x',expand=False)
txt.config(xscrollcommand=scr1.set)
scr1.config(command=txt.xview)


root.mainloop()

tkinterText小部件中没有wraplength选项。但是,您可以使用tag_configure()rmargin选项模拟效果。

下面是一个使用rmargin选项的自定义文本小部件示例:

import tkinter as tk
from tkinter import font
class MyText(tk.Text):
def __init__(self, master=None, **kw):
self.wraplength = kw.pop('wraplength', 80)
# create an instance variable of type font.Font
# it is required because Font.measure() is used later
self.font = font.Font(master, font=kw.pop('font', ('Consolas',12)))
super().__init__(master, font=self.font, **kw)
self.update_rmargin() # keep monitor and update "rmargin"
def update_rmargin(self):
# determine width of a character of current font
char_w = self.font.measure('W')
# calculate the "rmargin" in pixel
rmargin = self.winfo_width() - char_w * self.wraplength
# set up a tag with the "rmargin" option set to above value
self.tag_config('rmargin', rmargin=rmargin, rmargincolor='#eeeeee')
# apply the tag to all the content
self.tag_add('rmargin', '1.0', 'end')
# keep updating the "rmargin"
self.after(10, self.update_rmargin)
root = tk.Tk()
textbox = MyText(root, width=100, font=('Consolas',12), wrap='word', wraplength=90)
textbox.pack(fill='both', expand=1)
# load current file
with open(__file__) as f:
textbox.insert('end', f.read())
root.mainloop()

请注意,我使用了after(),因此即使内容发生了更改,rmargin选项也会应用于更新的内容。

还要注意,这可能不是一种有效的方式,但它显示了一种可能的方式。

最新更新