简体   繁体   English

如何获取Tkinter Text小部件中Text的当前长度

[英]How do I get the current length of the Text in a Tkinter Text widget

I am writing a light webtexting application, and I'm trying to display the current number of characters in a TKinter Text widget used for writing the message to be sent in the webtext. 我正在编写一个轻量级的webtexting应用程序,我试图在TKinter Text小部件中显示当前的字符数,用于编写要在webtext中发送的消息。 The code I have at the moment can be seen below, I'm using python 我现在的代码可以在下面看到,我正在使用python

root = Tk()

msgLabel = Label(text="Message")
msgLabel.grid(row=0, column=0)
msg = Text(width=40, height=4, wrap="word")
msg.grid(row=0, column=1, padx=10, pady=5)

#Try to display number of characters within message to user
charCount = Label(text="Character Count: "+str(len(meg.get("1.0", 'end-1c')))
charCount.grid(row=1, column=1, pady=5, padx=5)

root.mainloop()

I'd like to be able to display the number of characters in the message written by the user, since there is a 160 character limit to each webtext. 我希望能够显示用户写入的消息中的字符数,因为每个webtext有160个字符的限制。 Is it possible to display the current character length, that updates as text is inserted and removed? 是否可以显示当前字符长度,在插入和删除文本时更新? Thanks in advance 提前致谢

We use StringVar to set the new text to the label. 我们使用StringVar将新文本设置为标签。 We need to bind msg for key pressing. 我们需要绑定msg以进行按键操作。

from Tkinter import *
root = Tk()

def update(event):
    var.set(str(len(msg.get("1.0", 'end-1c'))))

msgLabel = Label(text="Message")
msgLabel.grid(row=0, column=0)
msg = Text(width=40, height=4, wrap="word")
msg.grid(row=0, column=1, padx=10, pady=5)

var = StringVar()

#Try to display number of characters within message to user
charCount = Label(textvariable=var)
charCount.grid(row=1, column=1, pady=5, padx=5)

msg.bind("<KeyRelease>", update)

root.mainloop()

In below example, the character count in the text is displayed in the label above at all times. 在下面的示例中, text的字符数始终显示在上面的label

try:
    import tkinter as tk
except:
    import Tkinter as tk


def on_every_keyboard_input(event):
    update_char_length(text, label)


def update_char_length(text_widget, display_widget):
    string_in_text = text_widget.get('1.0', 'end-1c')
    string_length = len(string_in_text)
    display_widget['text'] = string_length


if __name__ == '__main__':
    root = tk.Tk()
    text = tk.Text(root)
    label = tk.Label(root, text=0, justify='center')

    text.bind('<KeyPress>', on_every_keyboard_input)
    text.bind('<KeyRelease>', on_every_keyboard_input)

    label.pack()
    text.pack()
    root.mainloop()

Below is a tiny example, in which the character count in the text is displayed in label above at all times. 下面是一个很小的例子,其中text的字符数始终显示在上面的label

try:
    import tkinter as tk
except:
    import Tkinter as tk


if __name__ == '__main__':
    def update(event):
        label['text'] = len(text.get('1.0', 'end-1c'))


    root = tk.Tk()
    text = tk.Text(root)
    label = tk.Label(root, text=0, justify='center')

    text.bind('<KeyPress>', update)
    text.bind('<KeyRelease>', update)

    label.pack()
    text.pack()
    root.mainloop()

Below script defines a class, TextWithCharLength , which has a Text and a Label in which the character length of the content in the text is displayed: 下面的脚本定义了一个TextWithCharLength类,它有一个Text和一个Label ,其中显示了text内容的字符长度:

try:
    import tkinter as tk
except:
    import Tkinter as tk


class TextWithCharLength(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self._events = ('<KeyPress>',
                        '<KeyRelease>',
                        '<ButtonRelease-1>',
                        '<ButtonRelease-2>',
                        '<ButtonRelease-3>',
                        '<Delete>',
                        '<<Cut>>',
                        '<<Paste>>',
                        '<<Undo>>',
                        '<<Redo>>')
        self._create_widgets()
        self._widgets_layout()
        self.update_char_len(event=None)
        self.bind_events_on_widget_to_callback( self._events,
                                                self.text,
                                                self.update_char_len)

    def _create_widgets(self):
        self.label = tk.Label(self, justify='center')
        self.text = tk.Text(self)


    def _widgets_layout(self):
        self.label.pack(fill='x', expand=True)
        self.text.pack(fill='both', expand=True)


    @staticmethod
    def bind_events_on_widget_to_callback(events, widget, callback):
        """ Bind events on widget to callback.
        """

        for _event in events:
            widget.bind(_event, callback)


    def update_char_len(self, event):
        """ Update self.label's text with character length of content
        in self.text.
        """

        self.label['text'] = len(self.text.get('1.0', 'end-1c'))


if __name__ == '__main__':
    root = tk.Tk()
    text_frame = TextWithCharLength(root)
    text_frame.pack()
    root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Tkinter 文本小部件中的文本中获取标签? - How do you get the tags from text in a Tkinter text widget? Tkinter:如何隐藏文本,就像使用带有文本(而非输入)小部件的密码一样? - Tkinter: How do I hide text as if with a password with a Text (not Entry) widget? 如何在 Tkinter 文本小部件中居中文本? - How do I center text in the Tkinter Text widget? 如何在当前选项卡的文本小部件中插入文本? - How do I insert text into the Text widget in the current tab? 如何将焦点放在python Tkinter文本小部件上? - How do I give focus to a python Tkinter text widget? 如何设置Tkinter.Text小部件滚动条的宽度? - How do I set the width of a Tkinter.Text widget scrollbar? 如何在 tkinter Text 小部件中实现查找和替换功能? - How do I implement a find and replace function in a tkinter Text widget? 在 Python Tkinter 中,如何使用名称获取嵌入在文本小部件中的图像的索引? - In Python Tkinter, how do I get the index of an image embedded in a text widget using the name? 如何从 Tkinter Text Widget 获取输入? - How to get the input from the Tkinter Text Widget? 如何通过阻止输入的最新字符来限制 python 中 tkinter 文本小部件的长度? - how do you restrict the length of a tkinter text widget in python by blocking the latest character entered?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM