Home > Back-end >  tkinter Problem: When an if conditional is wrong but still right?
tkinter Problem: When an if conditional is wrong but still right?

Time:10-22

tl,dr: An if conditional is activated when I know the condition is not TRUE.

This is probably a question about python in general, but I came across this using tkinter, so i'm sticking with that. I was trying to understand code I got from here, when I found this problem (I stripped it down to make it plain):

import tkinter as tk

after_id = None

def post():
    global after_id
    if after_id:
        print('How can this print if \"after_id == True\" is '   str(after_id == True))
        
root = customtkinter.CTk()
after_id = root.after(500, post)

root.mainloop()

Evidently, this does print, and as you can see, after_id is not TRUE, it is not even Boolean. This sort of flies against everything I thought I knew about if statements. Can someone please explain to me what is going on here?

CodePudding user response:

I just learned that all string statements except for an empty string are considered true in python. This is true for many non-empty objects apparently. Hope I didn't waste anyones time.

CodePudding user response:

In python, an object undergoes a truth testing procedure. Look here for more information. It basically states:

  1. An object that is a boolean is evaluated True or False
  2. Integers with a value of 1 are True whereas 0 is False
  3. Empty data structures, None, etc. are mostly interpreted as False.

CodePudding user response:

There might be a couple of problems:

  1. you imported tkinter as tk and should call tk.TK() instead of customtkinter.CTk() in root.

  2. after_id should have a boolean value of True or False. In this case, the default value is False

  3. (IMPORTANT) when you call root.after(500, post) this code will run and the reading of the file will not proceed, so when you run the file, it will reach this part and will not continue to root.mainloop() (it happened with me once)

I hope this helps :)

  • Related