| Conditions | 2 |
| Total Lines | 61 |
| Code Lines | 28 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | import platform |
||
| 70 | for choice, value in listbox_chooser.get_choices(): |
||
| 71 | print(choice, value) |
||
| 72 | ``` |
||
| 73 | """ |
||
| 74 | |||
| 75 | def __init__(self, window_title: str, options: dict, default=None): |
||
| 76 | super().__init__(window_title) |
||
| 77 | self.exit_button = None |
||
| 78 | self.choices = list(options.keys()) |
||
| 79 | self.options = options |
||
| 80 | self.default = default |
||
| 81 | self.selection_var = tk.Variable(self) |
||
| 82 | self.create_widgets() |
||
| 83 | self.mainloop() |
||
| 84 | |||
| 85 | def create_widgets(self): |
||
| 86 | frame = ttk.Frame(self) |
||
| 87 | frame.pack(padx=2, pady=2) |
||
| 88 | |||
| 89 | listbox = tk.Listbox(frame, listvariable=tk.Variable(self, value=self.choices), selectmode="multiple", |
||
| 90 | height=min(len(self.choices), 50), width=max(len(c) for c in self.choices)) |
||
| 91 | listbox.pack(side=tk.LEFT, fill=tk.BOTH) |
||
| 92 | |||
| 93 | scrollbar = ttk.Scrollbar(frame, command=listbox.yview) |
||
| 94 | scrollbar.pack(side=tk.RIGHT, fill=tk.BOTH) |
||
| 95 | listbox.config(yscrollcommand=scrollbar.set) |
||
| 96 | |||
| 97 | listbox.bind("<<ListboxSelect>>", self.on_select) |
||
| 98 | |||
| 99 | self.exit_button = ttk.Button(self, text="OK", command=self.destroy, state=tk.DISABLED) |
||
| 100 | self.exit_button.pack(pady=4, side=tk.BOTTOM) |
||
| 101 | |||
| 102 | def on_select(self, event): |
||
| 103 | self.exit_button['state'] = tk.NORMAL |
||
| 104 | self.selection_var.set(event.widget.curselection()) |
||
| 105 | |||
| 106 | def get_choices(self): |
||
| 107 | for choice in self.selection_var.get(): |
||
| 108 | yield self.choices[choice], self.options.get(self.choices[choice], self.default) |
||
| 109 |