Search code examples
python-3.xfor-looptkintertabsttk

why does my tk tabbed for loop have an error of "tabs[upper_tabs] = self.tab TypeError: unhashable type: 'list'"


I can create the 2 tabs individually, and I am trying to make it expendable by using a for loop. I get an error that says

tabs[upper_tabs] = self.tab
TypeError: unhashable type: 'list'

I am assuming it's how I reference the dictionary. Would you please help me understand and correct the error.

import tkinter as tk 
from tkinter import ttk

upper_tabs = ["Final", "Requests"]
tabs = {}

class Application(ttk.Frame): #inherent from frame.
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, bg="ivory2")
        self.parent = parent
        self.pack()

    self.tabControl = ttk.Notebook(self, width="900", height= "350") # 
       Create Tab Control

    for names in upper_tabs:
        self.tab=ttk.Frame(self.tabControl)# Create a tab
        self.tabControl.add(self.tab, text=names)      # Add the tab
        tabs[names] = self.tab
        self.tabControl.pack(expand=1, fill="both")  # Pack to make visible
        self.grid()

def main():
    root = tk.Tk()
    root.title("class basic window")
    root.geometry("1200x600")
    root.config(background="LightBlue4")
    app = Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Solution

  • I don't quite understand what you want to do, but to remove the error and make the program look like this... enter image description here (Scaled down) ... is to change the line tabs[upper_tabs] = self.tab to tabs[tuple(upper_tabs)] = self.tab.

    This works because a tuple cannot change, and it is, therefore, possible to use it as a dictionary key, which a list can't be. For more on python dictionaries, see this page.