How to pop up tkinter message box once?

Advertisements

I’m struggling to figure out how to show warning only once in tkinter if self.rmn <= 10. Because I’m using after() the message is showing every second. How to show message once please help.

here is my code:

def setinitqty(self):
    if self.btqty.get() == '':
        msg.showerror('Error','Set Bt Address Quantity')
        
    else:
        self.count = 0
        with open('C:/Users/user/Desktop/Test/test.txt','r') as f:
            for line in f:
                if line.strip():
                    self.count += 1
        self.prntbtadd = self.count
        self.initqty = self.btqty.get()
        self.setbtn['state'] = 'disable'
        self.btqty['state'] = 'disable'
        self.rstbtn['state'] = 'active'
        self.rmn = int(self.initqty) - self.prntbtadd
        self.rmnqtylbl['text'] = str(self.rmn)
        self.rmnqtylbl.after(1000,self.setinitqty)
        if self.rmn <= 10:
            msg.showwarning('Warning','Warning')
            self.rmnbtaddfrm['bg'] = 'red'
            self.rmnqtylbl['bg'] = 'red'

>Solution :

Here’s how to use a global flag variable as I suggested in my comment — to a certain degree it’s a guess, since I can’t test it since you didn’t post a runnable minimal, reproducible example.

warning_shown = False  # Define global variable.

class MyClass:
    ...

    def setinitqty(self):
        global warning_shown  # IMPORTANT.

        if self.btqty.get() == '':
            msg.showerror('Error','Set Bt Address Quantity')
        else:
            self.count = 0
            with open('C:/Users/user/Desktop/Test/test.txt','r') as f:
                for line in f:
                    if line.strip():
                        self.count += 1
            self.prntbtadd = self.count
            self.initqty = self.btqty.get()
            self.setbtn['state'] = 'disable'
            self.btqty['state'] = 'disable'
            self.rstbtn['state'] = 'active'
            self.rmn = int(self.initqty) - self.prntbtadd
            self.rmnqtylbl['text'] = str(self.rmn)
            self.rmnqtylbl.after(1000,self.setinitqty)
            if self.rmn <= 10:
                if not warning_shown:
                    msg.showwarning('Warning','Warning')
                    warning_shown = True
                    self.rmnbtaddfrm['bg'] = 'red'
                    self.rmnqtylbl['bg'] = 'red'

Leave a ReplyCancel reply