python-3.xtkinterlogiclogical-operatorstkinter-menu

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


so I created a Python file where the user can turn on word count and it will display the number of characters and words. It will also put a check mark near that option when it is enabled. Whenever, the user clicks the option twice it removes the check mark. However, it does not stop counting the words and characters, how would I do this?

This is the code for the word count function:

# 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)

This is the code for the menu:

# 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)

How would I get the status bar to stop displaying word and character count when the check mark is not there?


Solution

  • You should perform the word count and call .after() only when WordWrap_CheckMark is set to True:

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

    Note that there is typo in the line:

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

    It should be

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