0

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

import tkinter as tk

class textEditor(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **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()
4

3 回答 3

1

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

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

import tkinter as tk

class textEditor(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **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()
于 2021-06-21T06:00:53.670 回答
1

不要调用()您要绑定的函数。它作为参数传递,用作回调

使用正则表达式在 Python 中计算字数

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

class textEditor( tk .Frame ):
    def __init__( self, *args, **kwargs ):
        tk .Frame .__init__( self, *args, **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()
于 2021-06-21T05:45:39.097 回答
0

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

def keypress( self, ev ):
    if len( ev.keysym ) == 1:
        print( ev.keysym, end='' )
于 2021-06-21T05:40:03.700 回答