gpt4 book ai didi

python - 在 Tkinter 中自动换行文本的单行文本输入 UI 元素?

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:38 33 4
gpt4 key购买 nike

我的用户界面需要接受一行文本。但是,如果文本的长度超过 UI 元素的宽度,则文本应换行到下一行。

Tkinter Entry 类提供了我正在寻找的关于接受单行文本的内容。但是,如果文本超过元素的宽度,则文本不会换行。相反,它向左滚动。这可以防止用户看到前几个字符是什么。

Tkinter Text 类支持自动换行,但它也允许用户输入换行符。我的文本需要作为单行输入。

我正在寻找介于两者之间的东西:一个 UI 元素,它接受单行文本(没有换行符),但当输入溢出元素的宽度时也会换行。

我有哪些选择?

最佳答案

没有这样的小部件,但你可以这样做:

import tkinter as tk

class ResizableText:
def __init__(self, text_max_width=20):
self.text_width = text_max_width
self.root = tk.Tk()

self.text = tk.Text(self.root, width=self.text_width, height=1)
self.text.pack(expand=True)

self.text.bind("<Key>", self.check_key)
self.text.bind("<KeyRelease>", self.update_width)

self.root.mainloop()

def check_key(self, event):
# Ignore the 'Return' key
if event.keysym == "Return":
return "break"

def update_width(self, event):
# Get text content; ignore the last character (always a newline)
text = self.text.get(1.0, tk.END)[:-1]
# Calculate needed number of lines (=height)
lines = (len(text)-1) // self.text_width + 1
# Apply changes on the widget
self.text.configure(height=lines)

关于python - 在 Tkinter 中自动换行文本的单行文本输入 UI 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819426/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com