Saltar al contenido

¿La aplicación tkinter agrega un menú contextual de clic derecho?

Estate atento ya que en este post encontrarás la solución que buscas.Esta crónica ha sido probado por nuestros especialistas para garantizar la calidad y veracidad de nuestro contenido.

Solución:

Debería crear una instancia de Menú y escribir una función que llame
su post() o tk_popup() método.

La documentación de tkinter actualmente no tiene ninguna información sobre tk_popup().
Lea la documentación de Tk para obtener una descripción o la fuente:

library/menu.tcl en la fuente Tcl / Tk:

::tk_popup --
This procedure pops up a menu and sets things up for traversing
the menu and its submenus.

Arguments:
menu  - Name of the menu to be popped up.
x, y  - Root coordinates at which to pop up the menu.  
entry - Index of a menu entry to center over (x,y).  
        If omitted or specified as , then menu's  
        upper-left corner goes at (x,y).  

tkinter/__init__.py en la fuente de Python:

def tk_popup(self, x, y, entry=""):
    """Post the menu at position X,Y with entry ENTRY."""
    self.tk.call('tk_popup', self._w, x, y, entry)

Usted asocia la función de invocación del menú contextual con el clic derecho a través de:
the_widget_clicked_on.bind("", your_function).

Sin embargo, el número asociado con el clic derecho no es el mismo en todas las plataformas.

library/tk.tcl en la fuente Tcl / Tk:

On Darwin/Aqua, buttons from left to right are 1,3,2.  
On Darwin/X11 with recent XQuartz as the X server, they are 1,2,3; 
other X servers may differ.

Aquí hay un ejemplo que escribí que agrega un menú contextual a un Listbox:

import tkinter # Tkinter -> tkinter in Python 3

class FancyListbox(tkinter.Listbox):

    def __init__(self, parent, *args, **kwargs):
        tkinter.Listbox.__init__(self, parent, *args, **kwargs)

        self.popup_menu = tkinter.Menu(self, tearoff=0)
        self.popup_menu.add_command(label="Delete",
                                    command=self.delete_selected)
        self.popup_menu.add_command(label="Select All",
                                    command=self.select_all)

        self.bind("", self.popup) # Button-2 on Aqua

    def popup(self, event):
        try:
            self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popup_menu.grab_release()

    def delete_selected(self):
        for i in self.curselection()[::-1]:
            self.delete(i)

    def select_all(self):
        self.selection_set(0, 'end')


root = tkinter.Tk()
flb = FancyListbox(root, selectmode='multiple')
for n in range(10):
    flb.insert('end', n)
flb.pack()
root.mainloop()

El uso de grab_release() se observó en un ejemplo en effbot.
Es posible que su efecto no sea el mismo en todos los sistemas.

Hice algunos cambios en el código del menú de texto anterior para ajustar mi demanda y creo que sería útil compartir:

Versión 1:

import tkinter as tk
from tkinter import ttk

class Main(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        master.geometry('500x350')
        self.master = master
        self.tree = ttk.Treeview(self.master, height=15)
        self.tree.pack(fill='x')
        self.btn = tk.Button(master, text='click', command=self.clickbtn)
        self.btn.pack()
        self.aMenu = tk.Menu(master, tearoff=0)
        self.aMenu.add_command(label='Delete', command=self.delete)
        self.aMenu.add_command(label='Say Hello', command=self.hello)

        # attach popup to treeview widget
        self.tree.bind("", self.popup)

    def clickbtn(self):
        text = 'Hello ' + str(self.num)
        self.tree.insert('', 'end', text=text)
        self.num += 1

    def delete(self):
        print(self.tree.focus())
        if self.iid:
            self.tree.delete(self.iid)

    def hello(self):
        print ('hello!')

    def popup(self, event):
        self.iid = self.tree.identify_row(event.y)
        if self.iid:
            # mouse pointer over item
            self.tree.selection_set(self.iid)
            self.aMenu.post(event.x_root, event.y_root)            
        else:
            pass

Versión 2:

import tkinter as tk
from tkinter import ttk

class Main(tk.Frame):
    def __init__(self, master):
        master.geometry('500x350')
        self.master = master
        tk.Frame.__init__(self, master)
        self.tree = ttk.Treeview(self.master, height=15)
        self.tree.pack(fill='x')
        self.btn = tk.Button(master, text='click', command=self.clickbtn)
        self.btn.pack()
        self.rclick = RightClick(self.master)
        self.num = 0

        # attach popup to treeview widget
        self.tree.bind('', self.rclick.popup)
    def clickbtn(self):
        text = 'Hello ' + str(self.num)
        self.tree.insert('', 'end', text=text)
        self.num += 1

class RightClick:
    def __init__(self, master):

        # create a popup menu
        self.aMenu = tk.Menu(master, tearoff=0)
        self.aMenu.add_command(label='Delete', command=self.delete)
        self.aMenu.add_command(label='Say Hello', command=self.hello)

        self.tree_item = ''

    def delete(self):
        if self.tree_item:
            app.tree.delete(self.tree_item)

    def hello(self):
        print ('hello!')

    def popup(self, event):
        self.aMenu.post(event.x_root, event.y_root)
        self.tree_item = app.tree.focus()

root = tk.Tk()
app=Main(root)
root.mainloop()

Si posees algún titubeo o forma de regenerar nuestro enunciado te inspiramos ejecutar una ilustración y con placer lo estudiaremos.

¡Haz clic para puntuar esta entrada!
(Votos: 3 Promedio: 4)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *