emayecs | 5656b2b | 2021-08-04 12:44:13 -0400 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
emayecs | 5966a53 | 2021-07-29 10:07:02 -0400 | [diff] [blame] | 2 | # |
| 3 | # Simple listbox with scrollbar and select button |
| 4 | |
| 5 | import re |
| 6 | import tkinter |
| 7 | from tkinter import ttk |
| 8 | |
| 9 | class ListBoxChoice(ttk.Frame): |
| 10 | def __init__(self, parent, fontsize=11, *args, **kwargs): |
| 11 | ttk.Frame.__init__(self, parent, *args, **kwargs) |
| 12 | s = ttk.Style() |
| 13 | s.configure('normal.TButton', font=('Helvetica', fontsize), border = 3, relief = 'raised') |
| 14 | |
| 15 | def populate(self, title, list=[]): |
| 16 | self.value = None |
| 17 | self.list = list[:] |
| 18 | |
| 19 | ttk.Label(self, text=title).pack(padx=5, pady=5) |
| 20 | |
| 21 | listFrame = ttk.Frame(self) |
| 22 | listFrame.pack(side='top', padx=5, pady=5, fill='both', expand='true') |
| 23 | |
| 24 | scrollBar = ttk.Scrollbar(listFrame) |
| 25 | scrollBar.pack(side='right', fill='y') |
| 26 | self.listBox = tkinter.Listbox(listFrame, selectmode='single') |
| 27 | self.listBox.pack(side='left', fill='x', expand='true') |
| 28 | scrollBar.config(command=self.listBox.yview) |
| 29 | self.listBox.config(yscrollcommand=scrollBar.set) |
| 30 | self.list.sort(key=natsort_key) |
| 31 | for item in self.list: |
| 32 | self.listBox.insert('end', item) |
| 33 | |
| 34 | if len(self.list) == 0: |
| 35 | self.listBox.insert('end', '(no items)') |
| 36 | else: |
| 37 | buttonFrame = ttk.Frame(self) |
| 38 | buttonFrame.pack(side='bottom') |
| 39 | |
| 40 | selectButton = ttk.Button(buttonFrame, text="Select", command=self._select, |
| 41 | style='normal.TButton') |
| 42 | selectButton.pack(side='left', padx = 5) |
| 43 | listFrame.bind("<Return>", self._select) |
| 44 | |
| 45 | def natsort_key(s, _nsre=re.compile('([0-9]+)')): |
| 46 | # 'natural' sort function. To make this alphabetical independently of |
| 47 | # capitalization, use "else text.lower()" instead of "else text" below. |
| 48 | return [int(text) if text.isdigit() else text for text in _nsre.split(s)] |
| 49 | |
| 50 | def _select(self, event=None): |
| 51 | try: |
| 52 | firstIndex = self.listBox.curselection()[0] |
| 53 | self.value = self.list[int(firstIndex)] |
| 54 | except IndexError: |
| 55 | self.value = None |
| 56 | |
| 57 | def value(self): |
| 58 | return self.value |