Search code examples
pythontkinterscalemessagebox

Infinite loop with tkinter messagebox and scale button (Python | Tkinter)


I accidentally created an infinite loop :D
With the function below I want to call a warning (if a file does not exist) when the user operates the tkinter Scale. This message should be displayed only once. But when the user clicks (in the middle) on the tkinter Scale button, the Scale button is dragged to the end and the message is called again and again.

How can I prevent this?

def change_max_y(v):

    try:
        # Some functions to check if the file exists
        # Open some json file
        # Do some calculation

    except FileNotFoundError:
        # Some function to open the messagebox:
        comment = tk.messagebox.askyesno('Title', "Something is missing.", icon='warning')
        
        if comment:
            # Do something
        else:
            return

ttk.Scale(settingsWin, orient=tk.HORIZONTAL, from_=0, to=4, length=110, command=change_max_y). \
    place(x=210, y=90)

Solution

  • You can define a global variable (i know it's bad practice, but sometimes it must be done) with a initial value of 0. In your callback function, you look if that variable is 0, if yes, you show your message box and set it to 1. If no, you do nothing. The code you provided modified accordingly :

    already_shown = 0
    
    def change_max_y(v):
    
        try:
            # Some functions to check if the file exists
            # Open some json file
            # Do some calculation
    
        except FileNotFoundError:
            # Some function to open the messagebox:
            if not already_shown:
                comment = tk.messagebox.askyesno('Title', "Something is missing.", icon='warning')
                already_shown = 1
            
                if comment:
                    # Do something
            else:
                return # note : you can delete this else statement, as the function 
                       # will return None by itself when there is nothing more to be
                       # done
    
    ttk.Scale(settingsWin, orient=tk.HORIZONTAL, from_=0, to=4, length=110, command=change_max_y). \
        place(x=210, y=90)