在 Tkinter 菜单中禁用复选标记时如何禁用功能?

How do you disable a function when a check mark is disabled in a Tkinter Menu?

所以我创建了一个 Python 文件,用户可以在其中打开字数统计,它会显示字符数和字数。启用后,它还会在该选项附近放置一个复选标记。每当用户单击该选项两次时,它就会删除复选标记。但是,它不会停止计算单词和字符,我该怎么做?

这是字数统计函数的代码:

# Word Count Function
def DeclareWordCount():

    # Turn of Word Count if the User Unchecks the Option in the Tools Menu

    # Get data in textbox - turns into a string
    TextContent = TextBox.get("1.0", END)
    # String to number 
    CharactersInTextBox = len(TextContent)    
    WordsInTextBox = len(TextContent.split()) 
    # Config in Status Bar
    StatusBar.config(text=str(CharactersInTextBox-1) + " Characters, " + str(WordsInTextBox) + " Words, ")

def InitWordCount():
    DeclareWordCount()
    StatusBar.after(1, InitWordCount)

这是菜单代码:

# Check Marks for Options in Tools Menu
WordWrap_CheckMark = BooleanVar()
WordWrap_CheckMark.set(False)

ToolsMenu = Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="Tools", menu=ToolsMenu, underline=0)
ToolsMenu.add_checkbutton(label="Word Count", onvalue=1, offvalue=0, variable=WordCount_CheckMark, command=InitWordCount)

当复选标记不存在时,如何让状态栏停止显示字数和字符数?

只有当 WordWrap_CheckMark 设置为 True 时才应执行字数统计并调用 .after():

def InitWordCount():
    if WordWrap_CheckMark.get():
        DeclareWordCount()
        StatusBar.after(1, InitWordCount)
    else:
        StatusBar.config(text="")

请注意该行有错别字:

ToolsMenu.add_checkbutton(..., variable=WordCount_CheckMark, ...)

应该是

ToolsMenu.add_checkbutton(..., variable=WordWrap_CheckMark, ...)