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

时间:2015-12-28 12:34:46

标签: python user-interface text tkinter widget

我正在编写一个轻量级的webtexting应用程序,我正在尝试在TKinter Text小部件中显示当前的字符数,用于编写要在webtext中发送的消息。我现在的代码可以在下面看到,我正在使用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()

我希望能够显示用户写入的消息中的字符数,因为每个webtext有160个字符的限制。是否可以显示当前字符长度,在插入和删除文本时更新?提前致谢

4 个答案:

答案 0 :(得分:4)

我们使用StringVar将新文本设置为标签。 我们需要绑定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()

答案 1 :(得分:1)

在下面的示例中,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()

答案 2 :(得分:0)

以下是一个很小的示例,其中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()

答案 3 :(得分:0)

下面的脚本定义了一个类TextWithCharLength,其中包含TextLabel,其中显示了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()