Skip to main content
 首页 » 编程设计

python之如何避免 tkinter ListboxSelect>> 和 .curselection() 在列表框之外检测事件/选择

2025年01月19日1098°冷暖

我正在使用以下 tkinter 小部件:Entry和 Listbox .我希望条目小部件在列表框中显示选定的项目列表框配置为允许 selectmode=tk.SINGLE .选择由 tkinter 内置虚拟事件触发 <<ListboxSelect>> .我的测试脚本如下所示。

Entry当 Listbox 时正确更新作出选择。但是,在 Listbox 之后我遇到了以下问题选择已发生:

  1. 当鼠标指针位于 Entry 时, 和一个 Left-Button Double Click发生导致选择 Entry 中的项目, 抛出 2 个异常。
  2. 如果鼠标指针放在除 tkinter GUI 之外的任何窗口上,例如在显示测试脚本的 IDLE 上或在终端上或......等,当我执行 Left-Button Double Click 时然后在该窗口中选择一个词,或者当我故意按下 Left Mouse Button 时选择一个段落,会出现 1. 中提到的相同异常(exception)情况。

错误如下所示。

注意:在 Listbox 中未进行选择时,不会出现上述问题。 .

如何避免这两个问题?我怀疑这些问题与 <<ListboxSelect>> 有关和 widget.curselection()允许在 Listbox 之外触发但不知道如何进一步调查。

我想要发生什么?

  1. 鼠标指针在其他窗口或未超过时的事件Listbox不应注册。
  2. 双击 Entry不应影响 Listbox 中的选择.

谢谢。

测试脚本:

import tkinter as tk 
 
class App(tk.Tk): 
    def __init__(self): 
        tk.Tk.__init__(self) 
        self.entrytext = tk.StringVar() 
        self.entry = tk.Entry(textvariable=self.entrytext) 
        self.listbox = tk.Listbox(selectmode=tk.SINGLE) 
        self.entry.pack(side="top", fill="x") 
        self.listbox.pack(side="top", fill="both", expand=True) 
        for i in range(100): 
            self.listbox.insert("end", "item %s" % i) 
        self.listbox.bind("<<ListboxSelect>>", self.ListboxSelect) 
 
 
    def ListboxSelect(self, event): 
        widget = event.widget 
        try: 
            selection=widget.curselection() 
            print('\nselection = ', selection) 
            selection_index = int(selection[0]) 
            print('selection_index = ', selection_index) 
            selection_value = widget.get(selection[0]) 
            print("selection_value = {} ".format(selection_value)) 
            self.entrytext.set(selection_value) 
        except: 
            raise 
 
 
if __name__=='__main__': 
    a = App() 
    a.grid() 

异常(exception)情况:

Exception in Tkinter callback 
Traceback (most recent call last): 
  File "/usr/lib/python3.5/idlelib/run.py", line 119, in main 
    seq, request = rpc.request_queue.get(block=True, timeout=0.05) 
  File "/usr/lib/python3.5/queue.py", line 172, in get 
    raise Empty 
queue.Empty 
 
During handling of the above exception, another exception occurred: 
 
Traceback (most recent call last): 
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__ 
    return self.func(*args) 
  File "~/entry_listbox_example.py", line 22, in ListboxSelect 
    selection_index = int(selection[0]) 
IndexError: tuple index out of range 

请您参考如下方法:

How to avoid tkinter <<ListboxSelect>> and .curselection() detecting events/selection outside of Listbox?

这完全取决于您的意思。 <<ListboxSelect>>事件被明确设计为在列表框中的选择发生变化时触发,无论它如何变化。这可能意味着用户在列表框中选择了新内容,或者从列表框中删除了选择。

你得到的错误是因为你假设有一个选择,这可能是也可能不是真的。您需要检查选择,并且只有在选择了某些内容时才运行您的代码。

另一个解决方案,或整体解决方案的一部分,可能是设置 exportselection列表框的选项为 False .当设置为 True 时-- 默认值 -- 只要任何其他小部件获得选择,该选择将被取消设置。当设置为 False 时,选择不会因为另一个小部件选择了它的部分或全部数据而改变。