Why is this not giving me the selected item in the listbox?

In my whole program I have this function, please read this code instead of executing because many variables are created outside the function and sending all of that code would reach over 100 lines which aren’t required. In my tkinter program I am making a Listbox which has the names of some files, while opening the file I try to get the selected item in the Listbox but I am not getting the selected item, anyone know why?

def open_maze(event):

	mazes_window = Toplevel(root)
	mazes_window.config(bg = "black")

	Label(mazes_window, text = "Choose a maze", bg = "black", fg = "white").pack(side = "top")

	x_lb_scrollbar = Scrollbar(mazes_window, orient = "vertical")
	y_lb_scrollbar = Scrollbar(mazes_window, orient = "horizontal")
	mazes = Listbox(mazes_window, bg = bg, fg = "white", yscrollcommand = y_lb_scrollbar.set, xscrollcommand = x_lb_scrollbar.set, selectmode = "SINGLE")

	cwd = os.getcwd()
	os.chdir("C:\\Users\\" + login + "\\Desktop\\Project_Arck\\Path Finder\\mazes")

	for x in os.listdir():

		mazes.insert("end", x)

	def build_new_maze():



		# try:
		with open(mazes.get("active"))as f:

			settings.settings[mapcode] = eval(f.read())


		# except Exception as e:

		# 	showerror("Corrupted file", "the maze data is corrupted")
		# 	print(e)

	open_maze_button = Button(mazes_window, text = "Open", bg = "black", fg = "white", command = build_new_maze)
	open_maze_button.pack(side = "bottom", fill = "x")

	x_lb_scrollbar.pack(side = "right", fill = "y")
	y_lb_scrollbar.pack(side = "bottom", fill = "x")
	mazes.pack(fill = "both", expand = True)

	x_lb_scrollbar.config(command = mazes.xview)
	y_lb_scrollbar.config(command = mazes.yview)

Here’s the error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\DEVDHRITI\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\DEVDHRITI\Desktop\Project_Arck\Path Finder\Path_Finder.pyw", line 293, in build_new_maze
    with open(mazes.get("active"))as f:
  File "C:\Users\DEVDHRITI\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 3216, in get
    return self.tk.call(self._w, 'get', first)
_tkinter.TclError: invalid command name ".!toplevel.!listbox"

When you call mazes_window.destroy(), that destroys the entire window and everything inside it - including the listbox widget. The objects still exist, but they’re in a “dead” state where they can’t do anything. What you should do instead is call mazes_window.withdraw(), which makes it look like the window closed but actually just hides it from view. You could destroy it after you’ve read off the widget value.

1 Like

Thank you so much!!