There's more...

The postcommand option allows you to reconfigure a menu each time it is displayed with the post method. To illustrate how to use this option, we will disable the cut, copy, and delete entries if there is no current selection in the Text widget and disable the paste entry if there are no contents in the clipboard.

Like the rest of our callback functions, we pass a reference to a method of our class to add this configuration option:

def __init__(self):
super().__init__()
self.menu = tk.Menu(self, tearoff=0,
postcommand=self.enable_selection)

Then, we check whether the SEL range exists to determine whether the state of the entries should be ACTIVE or DISABLEDThis value is passed to the entryconfig method, which takes the index of the entry to configure as its first argument, and the list of options to be updated—remember that menu entries are 0 indexed:

def enable_selection(self):
state_selection = tk.ACTIVE if self.text.tag_ranges(tk.SEL)
else tk.DISABLED
state_clipboard = tk.ACTIVE
try:
self.clipboard_get()
except tk.TclError:
state_clipboard = tk.DISABLED

self.menu.entryconfig(0, state=state_selection) # Cut
self.menu.entryconfig(1, state=state_selection) # Copy
self.menu.entryconfig(2, state=state_clipboard) # Paste
self.menu.entryconfig(3, state=state_selection) # Delete

For instance, all the entries should be grayed out if there is no selection or if there are no contents on the clipboard:

With entryconfig, it is also possible to configure many other options, such as the label, font, and background. Refer to https://www.tcl.tk/man/tcl8.6/TkCmd/menu.htm#M48 for a complete reference of available entry options.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset