Popup Text Menu for CTkTextbox and CTkEntry Author: Akash Bora
| 2 | import tkinter |
| 3 | |
| 4 | class TextMenu(tkinter.Menu): |
| 5 | """ |
| 6 | Popup Text Menu for CTkTextbox and CTkEntry |
| 7 | Author: Akash Bora |
| 8 | """ |
| 9 | def __init__(self, |
| 10 | widget, |
| 11 | fg_color=None, |
| 12 | text_color=None, |
| 13 | hover_color=None, |
| 14 | **kwargs): |
| 15 | |
| 16 | super().__init__(tearoff=False, title="menu", borderwidth=0, bd=0, relief="flat", **kwargs) |
| 17 | |
| 18 | self.fg_color = customtkinter.ThemeManager.theme["CTkFrame"]["top_fg_color"] if fg_color is None else fg_color |
| 19 | self.text_color = customtkinter.ThemeManager.theme["CTkLabel"]["text_color"] if text_color is None else text_color |
| 20 | self.hover_color = customtkinter.ThemeManager.theme["CTkButton"]["hover_color"] if hover_color is None else hover_color |
| 21 | |
| 22 | self.widget = widget |
| 23 | |
| 24 | self.add_command(label="Cut", command=self.cut_text) |
| 25 | self.add_command(label="Copy", command=self.copy_text) |
| 26 | self.add_command(label="Paste", command=self.paste_text) |
| 27 | self.add_command(label="Delete", command=self.clear_text) |
| 28 | self.add_command(label="Clear All", command=self.clear_all_text) |
| 29 | self.add_command(label="Select All", command=self.select_all_text) |
| 30 | |
| 31 | self.add_command(label="Undo", command=self.undo_text) |
| 32 | |
| 33 | self.widget.bind("<Button-3>", lambda event: self.do_popup(event)) |
| 34 | self.widget.bind("<Button-2>", lambda event: self.do_popup(event)) |
| 35 | |
| 36 | def do_popup(self, event): |
| 37 | """ open the popup menu """ |
| 38 | |
| 39 | super().config(bg=self.widget._apply_appearance_mode(self.fg_color), |
| 40 | fg=self.widget._apply_appearance_mode(self.text_color), |
| 41 | activebackground=self.widget._apply_appearance_mode(self.hover_color)) |
| 42 | self.tk_popup(event.x_root, event.y_root) |
| 43 | |
| 44 | def cut_text(self): |
| 45 | """ cut text operation """ |
| 46 | self.copy_text() |
| 47 | try: self.widget.delete(tkinter.SEL_FIRST, tkinter.SEL_LAST) |
| 48 | except: pass |
| 49 | |
| 50 | def copy_text(self): |
| 51 | """ copy text operation """ |
| 52 | try: |
| 53 | self.clipboard_clear() |
| 54 | self.clipboard_append(self.widget.get(tkinter.SEL_FIRST, tkinter.SEL_LAST)) |
| 55 | except: pass |
| 56 | |
| 57 | def paste_text(self): |
| 58 | """ paste text operation """ |
| 59 | try: self.widget.insert(self.widget.index('insert'), self.clipboard_get()) |
| 60 | except: pass |
| 61 |