在输入 tkinter 文本小部件时在状态栏中显示字数

问题描述

我想做一个简单的文本编辑器,在我输入时显示唯一词的数量和总词数。我曾尝试使用 t.get("1.0","end-1c"),但我不知道如何进行交互(实时)。来自相关答案的玩具代码,其中 'keypress' 函数尝试将文本小部件的内容打印到终端,是:

import tkinter as tk

class textEditor(tk.Frame):
    def __init__(self,*args,**kwargs):
        tk.Frame.__init__(self,**kwargs)
        self.textFrm = tk.Frame(self)
        self.textFrm.pack(fill = "x")
        self.text = tk.Text(self.textFrm,relief = "flat",font = ("Arial","11"))
        self.text.pack(fill = "both",expand = True)
        self.text.bind('<keyrelease>',self.keyPress())
        self.text.focus()
    def keyPress(self):
        words = self.text.get("1.0","end-1c")
        print(words)

root = tk.Tk()
root.title("Text editor test")
t = textEditor(root)
t.pack()
root.mainloop()

解决方法

不要调用() 您要绑定的函数。它被作为参数传递以用作 callback

Word counts in Python using regular expression

#! /usr/bin/env python3
import tkinter as tk
import re

class textEditor( tk .Frame ):
    def __init__( self,*args,**kwargs ):
        tk .Frame .__init__( self,**kwargs )
        self .textFrm = tk .Frame( self )
        self .textFrm .pack( fill = 'x' )

        self .label = tk .Label( self )
        self .label .pack()

        self .text = tk .Text( self .textFrm,relief = 'flat',font = ('Arial','11') )
        self .text .pack( fill = 'both',expand = True )

        self .text .bind( '<KeyRelease>',self .keyPress )
        self .text .focus()

    def keyPress( self,event ):
        words = self .text .get( '1.0','end-1c' )
        wordcount = len( re .findall( '\w+',words ) )
        self .label .config( text = f'Words: {wordcount}' )

root = tk .Tk()
root .title( 'Text editor test' )
te = textEditor( root )
te .pack()
root .mainloop()
,

好的,当你 bind 一个函数时,不要调用它 - 不要使用 ()

这是一个有效的解决方案。每次按键都会更新状态栏

import tkinter as tk

class textEditor(tk.Frame):
    def __init__(self,**kwargs):
        tk.Frame.__init__(self,**kwargs)
        self.textFrm = tk.Frame(self)
        self.textFrm.pack(fill = "x")
        self.text = tk.Text(self.textFrm,relief = "flat",font = ("Arial","11"))
        self.text.pack(fill = "both",expand = True)
        self.text.bind('<KeyRelease>',self.keyPress)
        self.text.focus()
        self.status_bar=tk.Entry(self)
        self.status_bar.pack(fill = "x",side="top")
        
    def keyPress(self,event):
        words = self.text.get("1.0","end-1c")
        self.status_bar.delete(0,"end")
        self.status_bar.insert('end',words)

root = tk.Tk()
root.title("Text editor test")
t = textEditor(root)
t.pack()
root.mainloop()
,

绑定向函数发送事件,因此您需要将按键更改为。

def keypress( self,ev ):
    if len( ev.keysym ) == 1:
        print( ev.keysym,end='' )