I'm creating dictionary for myself in tkinter and when I added else statement (for any query that isn't in dictionary) it deleted first if statement (index).
I don't know exactly why. Entry (exe) works without any problems with else and index works with 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 be 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 with your code is that if the Entry text is 'index' then search_result
is set to "alea jacta est", as expected, but then your code goes on to test if the Entry text is 'exe', which it isn't, so the search_result
gets set to "Entry not in database.". You could prevent that second test by putting a return
statement on the line after the self.search_result.set("alea jacta est")
, but it's better to use the elif
technique.
If you have a lot of possible entry texts to test, it's more efficient to use a dictionary, with the entry text as the key and the result text as the value. Here's one way to do 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 is more efficient because dictionary lookup is fast, and relatively independent of the number of items in the dictionary.
In contrast, the if... elif...elif...
technique is making a linear search over all the possible strings until it finds a match, and that can get really slow if there are a lot of items to check, although it's ok if there are only a small number of items to check. OTOH, I find the dict
-based method more compact and easier to read & modify.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.