[英]How to make Text widgets adaptive in Tkinter?
Ok so let's say I've got a Text object. How can I make it so that it gets an extra line (or height + 1) whenever I fill in the current line?好吧,假设我有一个文本 object。我怎样才能让它在我填写当前行时得到一个额外的行(或高度 + 1)? like when it starts hiding the left of the line to show you the end?
比如当它开始隐藏行的左侧以显示结尾时?
Edit : since the question wasn't clear, I'll describe it more carefully.编辑:由于问题不清楚,我会更仔细地描述它。 Take this code as reference:
以此代码作为参考:
from tkinter import *
root = Tk()
text = Text(root, width=50, height=1)
text.pack
What it does, is creating a new Text widget of 1 line, and packs it.它所做的是创建一个新的 1 行文本小部件,并将其打包。 You may ask: Why don't you use the Entry widget?
您可能会问:为什么不使用 Entry 小部件? Because I want it to add more lines, instead of hiding what you already wrote to make some room for what you're writing, as shown below:
因为我希望它添加更多的行,而不是隐藏你已经写的内容来为你正在写的内容腾出一些空间,如下所示:
from tkinter import *
from threading import Thread
def adjustheight():
while True:
#check if whatever it's written takes more than a line to show
if takesmorethan1line == True:
text.config(height=(text.cget("height") + 1)
root = Tk()
text = Text(root, width=50, height=1)
text.pack
Thread(target = adjustheight).start()
root.mainloop()
I couldn't understand your question very well, But I assume that you have problem with wrapping a text.我不太明白你的问题,但我认为你在包装文本方面有问题。 For instance when you reduce the window size, the text should break into multi lines.
例如,当您减小 window 大小时,文本应该分成多行。 Here is as example:
这是例子:
import tkinter as tk
class MainWindow(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.my_label = tk.Label(
self, text="Helllllooooooooooooooooooooooooo")
self.my_label.bind('<Configure>',
lambda e: self.my_label.config(
wraplength=self.my_label.winfo_width()
))
self.my_label.pack()
self.mainloop()
if __name__ == '__main__':
window = MainWindow()
Line breaking , also known as word wrapping , is breaking a section of text into lines so that it will fit into the available width of a page, window or other display area, Read more.
换行,也称为自动换行,将一段文本分成几行,使其适合页面的可用宽度,window 或其他显示区域,阅读更多。
Tkinter's Text
widget have this feature already built in. wrap
is the option that will do it. Tkinter 的
Text
小部件已经内置了此功能wrap
是执行此操作的选项。
From the docs:从文档:
This option controls the display of lines that are too wide.
此选项控制太宽的线条的显示。 With the default behavior, wrap=tk.CHAR, any line that gets too long will be broken at any character.
使用默认行为 wrap=tk.CHAR,任何太长的行都将在任何字符处断开。
Set wrap=tk.WORD
and it will break the line after the last word that will fit.设置
wrap=tk.WORD
它将在最后一个适合的单词之后换行。
import tkinter as tk
root = tk.Tk()
text = tk.Text(root, wrap=tk.WORD)
text.pack(fill=tk.BOTH, expand=1)
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.