【问题标题】:How to disable selction of the free part of Tkinter Listbox widget as an item?如何禁用选择 Tkinter Listbox 小部件的免费部分作为项目?
【发布时间】:2020-08-25 02:18:07
【问题描述】:

我正在创建一个基于 Tkinter 的应用程序。它有一个列表框小部件,我想在双击时获得选定的项目。如果我双击一个项目,一切正常,但如果我双击列表框的空闲部分,最后一个项目将被选中,并且 curselection 返回一个包含它的元组(而不是一个空元组)。

代码如下:

from tkinter import *


root = Tk()
listbox = Listbox(root)
for item in ("foo", "bar"):
    listbox.insert(END, item)
listbox.bind("<Double-1>", lambda event: print(listbox.curselection()))
listbox.pack()
root.mainloop()

我也尝试按照@stovfl 的建议使用listbox.get(ACTIVE)listbox.nearest(event.y),但不幸的是,它也没有帮助。在第一种情况下,它返回列表框中显示的最后一个字符串,而不是具有最后一个索引的元组。在第二种情况下,它只返回最后一个索引而不是它的元组。

PS:我一直是here。但是我没有将事件绑定到根窗口,我将它绑定到列表框,但它也不能按我的需要工作。

【问题讨论】:

  • 继续阅读nearest(y)
  • @stovfl 感谢您的评论!如果我使用.get(ACTIVE),我不知道我可以立即获取活动元素而不是索引。但不幸的是,它也不起作用——我只得到最后一项而不是最后一个索引的元组。
  • @stovfl 再次感谢)我会看看它。
  • @stovfl 我试过listbox.nearest(event.y),但行为没有改变。现在它返回与我的问题图片中指定的元组中相同的索引 - 1.
  • jizhihaoSAMA, stovfl 非常感谢您的帮助!现在一切都很好! :)

标签: python tkinter


【解决方案1】:

我认为有两种方法可以实现:

  1. 当用户点击空白处时,取消选择active元素。(我不知道该怎么做)
  2. 或者判断鼠标的位置。

对于第二种解决方案(您可以使用函数Listbox.bbox()):

import tkinter as tk


class Custom(tk.Frame):
    def __init__(self, master):
        super(Custom, self).__init__()

        self.master = master
        self.listbox = tk.Listbox(master=self)
        self.pos_list = []
        for item in ("foo", "bar"):
            self.listbox.insert(tk.END, item)
        self.listbox.bind("<Double-1>", self.double_click)

        self.listbox.pack()

    def double_click(self, event): # judge the event.y and the position of the first offsetY and the last offsetY
        if (event.y < self.listbox.bbox(0)[1]) or (event.y > self.listbox.bbox(tk.END)[1]+self.listbox.bbox(tk.END)[3]): # if not between it
            print(None)
        else:
            print(self.listbox.nearest(event.y))


root = tk.Tk()
customFrame = Custom(root)
customFrame.pack()
root.mainloop()

参考:Listbox.bbox

【讨论】:

  • self.listbox.select_clear(tk.END, tk.END),见reply.it
猜你喜欢
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多