You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Listbox组件curselection()方法报错及索引无效TclError异常问题求助

Let's break down your two errors and fix them step by step:

First Error: curselection() missing 1 required positional argument: 'self'

The root cause here is two-fold:

  • Initially, you had lbox = Listbox (without parentheses) which assigned the Listbox class to lbox, not an instance of it. Calling lbox.curselection() tries to run the method on the class itself, which expects a self parameter (the instance) that doesn't exist.
  • Even after fixing that to lbox = Listbox(newWindow), the lbox in Show_fun() is a local variable—your Show() function can't access it, so it was still referring to the original class assignment (or an undefined variable, depending on scope).

Second Error: _tkinter.TclError: bad listbox index ""

This happens when:

  1. Show() is still accessing the wrong lbox (not the instance you created in Show_fun()), or
  2. You click the "Show" button without selecting any item in the listbox—curselection() returns an empty tuple, which get() can't process.

Fixed Solution (Cleaner, No Global Variables)

The best approach is to pass the listbox instance directly to the Show() function using a lambda, and add a check for selected items:

Modified Show() Function

def Show(lbox):
    # Check if any item is selected first
    selected_indices = lbox.curselection()
    if not selected_indices:
        # Optional: Add a popup message here for better UX
        print("Please select a site first!")
        return
    
    Selected = lbox.get(selected_indices[0])
    with open("pass.json","r+") as jfile:
        try:
            data = json.load(jfile)
            for i in data['Details']:
                if Selected == i["Site"]:
                    password_text.set(i["Password"])
                    uname_text.set(i["Username"])
        except JSONDecodeError:
            pass

Modified Show_fun() Button Line

In Show_fun(), update the Button command to pass the lbox instance directly:

Button(newWindow,text="Show",command=lambda: Show(lbox),fg="#00FF00",bg="black",pady=10).grid(row=4,column=1)

If you prefer using a global variable (works for small projects but isn't ideal for larger apps):

  1. Declare lbox as global in both functions:
# At the top of your script (outside any functions)
lbox = None

def Show():
    global lbox
    selected_indices = lbox.curselection()
    if not selected_indices:
        print("Please select a site first!")
        return
    Selected = lbox.get(selected_indices[0])
    # Rest of your existing code...

def Show_fun():
    global lbox
    newWindow = Toplevel(window)
    # ... rest of your code ...
    lbox = Listbox(newWindow)
    lbox.grid(row=1,column=2)
    # ... rest of your code ...

Key Fixes Explained

  • Passing the Listbox Instance: Using lambda: Show(lbox) ensures Show() uses the exact listbox you created in Show_fun(), eliminating scope confusion.
  • Checking for Selections: The if not selected_indices check prevents the TclError when the user clicks "Show" without picking a site.
  • Correct Instance Creation: Making sure lbox = Listbox(newWindow) (with parentheses) creates an actual Listbox object, not just a reference to the class.

内容的提问来源于stack exchange,提问作者War Hawk121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:42:31