Ethan Field
Ethan Field

Reputation: 4730

How to limit the number of selections in a tkinter listbox?

Say I had a piece of code like this:

from tkinter import *

master=Tk()

ListBox1 = Listbox(master, selectmode=MULTIPLE)

for Count in range(0, 5):
    ListBox1.insert(END, Count)

ListBox1.pack()

I was wondering whether it would be possible to limit the number of selected objects to something like 3 or 4. A quick google search and a read of the config options for listbox yielded no results and quite frankly I'm stumped as to how it could be possible to achieve these results.

Upvotes: 2

Views: 1857

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386285

Yes, it's possible. You have complete control over what is selected in the listbox. However, there's nothing built-in to support this so you'll have to write all the code that tracks the selection and disallows changing the selection based on some criteria. This would probably create a very confusing user experience since there's no way for the user to know that this standard-looking listbox has non-standard behavior.

Upvotes: 2

Ethan Field
Ethan Field

Reputation: 4730

So I reviewed this question again today and ended up writing a solution for it, almost three years on:

from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.listbox = Listbox(self.root, selectmode=MULTIPLE)
        self.listbox.pack()
        self.listbox.bind("<<ListboxSelect>>", self.callback)
        for i in range(10):
            self.listbox.insert(END, i)
        self.selection = self.listbox.curselection()
    def callback(self, a):
        if len(self.listbox.curselection()) > 3:
            for i in self.listbox.curselection():
                if i not in self.selection:
                    self.listbox.selection_clear(i)
        self.selection = self.listbox.curselection()

root = Tk()
App(root)
root.mainloop()

This creates an instance of the data after each check, and then checks against the previous instance to see whether there are any differences, then removes those differences.

Upvotes: 0

Related Questions