Python Forum
[Tkinter] What is the subscript error?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] What is the subscript error?
#1
Really, Really long script,
from tkinter import *

main = Tk()
main.title("1. Unit & Dimentions")

#root.geometry("1600x800+0+0")

result_txt = StringVar()
rel_result_txt = StringVar()

#Var Details
units_dict = {
    "fundamentals"                      :   "length, mass\ntime, current\ntemperature, amount of substance\nluminous intensity",
    "supplementary quantities"          :   "plane angle, solid angle\nradioactivity",
    "derived quantities"                :   "area, volume,\nvelocity, acceleration\nforce, density\nangle, strain\nrelative, angular velocity\nuniversal gravitational constant, coefficient of viscosity",
    "length"                            :   ["meter", "m", "L", "fundamentals"],
    "mass"                              :   ["kilogram" , "kg", "M", "fundamentals"],
    "time"                              :   ["second", "s", "T", "fundamentals"],
    "current"                           :   ["ampere", "A", "I", "fundamentals"],
    "temperature"                       :   ["kelvin", "K", "θ", "fundamentals"],
    "amount of substance"               :   ["mole", "mol", "N", "fundamentals"],
    "luminous intensity"                :   ["candela", "cd", "none", "fundamentals"],
    "plane angle"                       :   ["radian", "rad", "none", "supplementary quantities"],
    "solid angle"                       :   ["steradian", "sr", "none", "supplementary quantities"],
    "radioactivity"                     :   ["bequral", "Bq", "T⁻¹", "supplementary quantities"],
    "area"                              :   ["square meter", "m²", "L²", "derived quantities"],
    "volume"                            :   ["cubic meter" ,"m³", "L³", "derived quantities"],
    "velocity"                          :   ["meter per second", "ms⁻¹","LT⁻¹", "derived quantities"],
    "acceleration"                      :   ["meter per square second", "ms⁻²", "LT⁻²", "derived quantities"],
    "force"                             :   ["kilogram meter per square second", "kgms⁻² = N", "MLT⁻²", "derived quantities"],
    "density"                           :   ["kilogram meter per cubic second", "kgms⁻³", "ML⁻³", "derived quantities"],
    "angle"                             :   ["radian", "rad", "none", "derived quantities"],
    "strain"                            :   ["none", "none", "none", "derived quantities"],
    "relative"                          :   ["none", "none", "none", "derived quantities"],
    "angular velocity"                  :   ["radian per second", "rad s⁻¹", "T⁻¹", "derived quantities"],
    "universal gravitational constant"  :   ["newton square meter per square kilogram", "N m² kg⁻²", "M⁻¹L³T⁻²", "derived quantities"],
    "coefficient of viscosity"          :   ["newton second per square meter", "Nsm⁻²", "ML⁻¹T⁻¹", "derived quantities"],
}

#Text boxes
search_box = Entry(main, borderwidth = 4, width = 34)

#LblFrames
results = LabelFrame(main, text = "Results")
rel_results = LabelFrame(main, text = "Related Results")

#Text
name = Label(main, text = "1. Unit & Dimentions", font = ("arial", 45, "bold"), fg = "Steel Blue", bd = 10)
mj = Label(main, text = "A product of MihiraJ.com", font = ("arial", 26, "bold"), fg = "#cc5c54", bd = 10)
dev = Label(main, text = "Devloped by Oshadha Mihiranga", font = ("arial", 18, "bold"), fg = "Steel Blue", bd = 10)
search = Label(main, text = "Search", font = ("arial", 10, "bold"), fg = "black", bd = 10)
result_lbl = Label(results, textvariable = result_txt, justify = LEFT)
rel_restlts_lbl = Label(rel_results, textvariable = rel_result_txt, justify = LEFT)

#functions
def related_results(cater):
    prnt = units_dict.get(cater)
    rel_result_txt.set(prnt)
    rel_results.pack(fill = X, padx = 10)
    rel_restlts_lbl.pack(padx = 6, pady = 6, side = LEFT)

def search_start():
    results.pack(fill = X, padx = 10)
    clear_results.pack(pady = 4)
    txt_2_search = search_box.get().lower()
    global unit
    unit = units_dict.get(txt_2_search)
    if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities":
        if unit:
            result_txt.set(f"Physical Quantity : {txt_2_search}\nUnit : {unit[0]}\nSymbol : {unit[1]}\nDimention : {unit[2]}\nCategory : {unit[3]}")
            related_results(unit[3])
        else:
            result_txt.set(f"Err001 : Result not Found, Please type again.")
            search_box.delete(0, END)

    else:
        if unit:
            result_txt.set(f"{txt_2_search}\n{unit}")
        else:
            result_txt.set(f"Err001 : Result not Found, Please type again.")
            search_box.delete(0, END)

    search_box.delete(0, END)

def clear_res():
    clear_results.pack_forget()
    results.pack_forget()
    rel_results.pack_forget()
    result_txt.set("")

#buttons
search_button = Button(main, text = "Search", command = search_start)
clear_results = Button(main, text = "Clear", command = clear_res)

#pack
name.pack()
mj.pack()
search.pack()
search_box.pack()
search_box.focus()
search_button.pack()
result_lbl.pack(padx = 6, pady = 6, side = LEFT)
dev.pack(side = BOTTOM)

main.mainloop()
Error when I click search, when the text-box is clear, or -->(search_box.set("")
Error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1885, in __call__ return self.func(*args) File "D:\3. My folder\Projects\Programing\Python\4. MihiraJ Projects\Unit & Dimentions\1. Unit And Dimentions.py", line 68, in search_start if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities": TypeError: 'NoneType' object is not subscriptable
Reply
#2
when txt_2_search is not present in the dict keys, dict.get() will return default value of None. None[3] raise the exception you see.

Then there is one more problem in that line
if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities":
it will not work as you expect. see https://python-forum.io/Thread-Multiple-...or-keyword
Oshadha likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Jan-19-2021, 06:05 PM)buran Wrote: when txt_2_search is not present in the dict keys, dict.get() will return default value of None. None[3] raise the exception you see.

Then there is one more problem in that line
if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities":
it will not work as you expect. see https://python-forum.io/Thread-Multiple-...or-keyword

So what do I do?

Will this work?
def search_start():
    results.pack(fill = X, padx = 10)
    clear_results.pack(pady = 4)
    txt_2_search = search_box.get().lower()
    global unit
    unit = units_dict.get(txt_2_search)
    if unit == "" or "none":
        input_not_found()

    if unit[3] in ("fundamentals", "supplementary quantities", "derived quantities"):
        if unit:
            result_txt.set(f"Physical Quantity : {txt_2_search}\nUnit : {unit[0]}\nSymbol : {unit[1]}\nDimention : {unit[2]}\nCategory : {unit[3]}")
            related_results(unit[3])
        else:
            input_not_found()
    else:
        if unit:
            result_txt.set(f"{txt_2_search}\n{unit}")
        else:
            input_not_found()

    search_box.delete(0, END)
Reply
#4
You really need to stop asking all these questions and start figuring out how to solve the problems yourself.

This is an easy problem to solve. The error message tells you exactly what the error is and where it occurs.
Error:
File "...", line 68, in search_start if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities": TypeError: 'NoneType' object is not subscriptable
"Hmmm"", you think to yourself. "Why am I getting this subscriptable error? Since unit[3] is the only place I a musing a subscript, that must by the problem, but why? I am going to print out unit and see if that helps."

So you add a line to your code.
    unit = units_dict.get(txt_2_search)
    print("unit after units_dict.get", unit)
    if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities":
You run the program again, pressing the search button without first typing in a unit name. Now you get this:
Output:
unit after units_dict.get None Exception in Tkinter callback Traceback (most recent call last): File "...\tkinter\__init__.py", line 1885, in __call__ return self.func(*args) File "...1. Unit And Dimentions.py", line 68, in search_start if unit[3] == "fundamentals" or "supplementary quantities" or "derived quantities": TypeError: 'NoneType' object is not subscriptable
Before the error occurred you got something from the print statement. The output says that unit == None. Why is unit == None? Since unit is what gets retuned by the call units_dict.get(txt_2_search), it must be units_dict.get()that is returning None. I better read about the dictionary.get() function and see how it works. So you go read about dictionaries here:

https://docs.python.org/3/library/stdtyp...pesmapping

And you read this about get():

"get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError."

So that must mean that the key was not in the dictionary. That makes sense because I didn't enter anything for the search. I guess I'll have to modify my logic to prevent using a None result like a unit.

When you get into the mindset of fixing you own errors you will get better at not only finding problems, but at avoiding problems. Searching down a problem in the documentation and through experimentation is a great teacher. You will learn Python much faster and deeper that by asking an endless stream of questions.
buran likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to print subscript in TEXT using Graphics Shahnaz 5 4,360 Feb-23-2018, 07:19 AM
Last Post: Shahnaz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020