从Tkinter中的列表框中取消选择

时间:2017-05-09 02:30:53

标签: python tkinter listbox

我只是想知道如何从thinter的列表框中取消选择。每当我点击列表框中的某些内容时,它会突出显示并加下划线,但是当我向侧面点击屏幕时,列表框选择会保持突出显示。即使我单击按钮,选择仍然会加下划线。例如:在下面的示例代码中,单击其中一个后,我无法单击列表框选择。

from tkinter import *

def Add():
   listbox.insert(END, textVar.get())


root = Tk()

textVar = StringVar()
entry = Entry(root, textvariable = textVar)
add = Button(root, text="add", command = Add)
frame = Frame(root, height=100, width=100, bg="blue")
listbox = Listbox(root, height=5)
add.grid(row=0, column=0, sticky=W)
entry.grid(row=0, column=1, sticky=E)
listbox.grid(row=1, column=0)
frame.grid(row=1, column=1)

root.mainloop()

3 个答案:

答案 0 :(得分:2)

是的,这是列表框的正常行为。如果你想改变它,你可以在每次列表框离焦时调用clear函数:

listbox.bind('<FocusOut>', lambda e: listbox.selection_clear(0, END))

答案 1 :(得分:0)

使用“列表框”小部件上的selectmode参数。 您可以再次单击选定的项目,它将清除选择。

请参阅effbot链接: http://effbot.org/tkinterbook/listbox.htm

listbox = Listbox(root, height=5, selectmode=MULTIPLE)

答案 2 :(得分:0)

我设法创建了“列表框”小部件内所需的功能,以便当用户单击“列表框”中的同一项目或屏幕上其他位置时,取消选择当前选定的项目。解决方案非常简单。

最后,我创建了一个绑定,以便在窗口的任何位置按下鼠标左键时,都会执行取消选择列表框的功能。

root.bind('<ButtonPress-1>', deselect_item)

然后我创建了一个变量来存储要选择的最后一个列表框项目的值,并将其值初始化为None

previous_selected = None

然后,我定义了取消选择列表框的函数,如下所示。首先,选择新项目(用户刚刚单击的项目)并将其与先前选择的项目进行比较。如果为真,则用户单击了列表框中已经突出显示的项目,因此清除了列表框的选择,从而删除了所选项目。最后,该功能将先前选择的框更新为当前选择的框。

def deselect_item(event):
    if listbox.curselection() == previous_selected:
            listbox.selection_clear(0, tkinter.END)
    previous_selected = listbox.curselection()

以下(在python 3.8.0中)的完整示例如下:

import tkinter

class App(tkinter.Tk):
    def __init__(self):
        tkinter.Tk.__init__(self)
        self.previous_selected = None

        self.listbox = tkinter.Listbox(self)
        self.bind('<ButtonPress-1>', self.deselect_item)

        self.listbox.insert(tkinter.END, 'Apple')
        self.listbox.insert(tkinter.END, 'Orange')
        self.listbox.insert(tkinter.END, 'Pear')

        self.listbox.pack()

    def deselect_item(self, event):
        if self.listbox.curselection() == self.previous_selected:
                self.listbox.selection_clear(0, tkinter.END)
        self.previous_selected = self.listbox.curselection()

app = App()
app.mainloop()