python - If statement deleted by else statement in Tkinter -
i'm creating dictionary myself in tkinter , when added else statement (for query isn't in dictionary) deleted first if statement (index).
i don't know why. entry (exe) works without problems else , index works else deleted.
def search_button(self, event=none): if self.entry.get() == 'index': self.search_result.set("alea jacta est") if self.entry.get() == 'exe': self.search_result.set("lorem ipsum") else: self.search_result.set("entry not in database.")
your 2nd if
should elif
:
def search_button(self, event=none): if self.entry.get() == 'index': self.search_result.set("alea jacta est") elif self.entry.get() == 'exe': self.search_result.set("lorem ipsum") else: self.search_result.set("entry not in database.")
the problem code if entry text 'index' search_result
set "alea jacta est", expected, code goes on test if entry text 'exe', isn't, search_result
gets set "entry not in database.". could prevent second test putting return
statement on line after self.search_result.set("alea jacta est")
, it's better use elif
technique.
if have lot of possible entry texts test, it's more efficient use dictionary, entry text key , result text value. here's 1 way that:
texts = { "index": "alea jacta est", "exe": "lorem ipsum" } def search_button(self, event=none): result_text = texts.get(self.entry.get(), "entry not in database.") self.search_result.set(result_text)
the dictionary technique more efficient because dictionary lookup fast, , relatively independent of number of items in dictionary.
in contrast, if... elif...elif...
technique making linear search on possible strings until finds match, , can slow if there lot of items check, although it's ok if there small number of items check. otoh, find dict
-based method more compact , easier read & modify.
Comments
Post a Comment