问题
I'm using the notebook from tkinter.
And I need to close a tab when I'm doing a right click on it.
But I can't find a way to handle any event on it.
So I hope that someone can help me.
I just need an example, so if you need anything(code, etc) ask me.
回答1:
You can bind() event <Button-3> (right button) to notebook with function which will close selected tab.
nb = ttk.Notebook(root)
nb.bind('<Button-3>', on_click)
Problem is how to recognize clicked tab because tkinter sends only x, y.
Tcl/Tk has function indentity tab x y to convert x, y to tab index. But tkinter doesn't have it. You have to call Tcl command:
clicked_tab = nb.tk.call(nb._w, "identify", "tab", x, y)
and now you can use this index to close tab.
(you can see similar command indentify in ttk.py file)
Simple working example
import tkinter as tk
from tkinter import ttk
# --- functions ---
def on_click(event):
print('widget:', event.widget)
print('x:', event.x)
print('y:', event.y)
#selected = nb.identify(event.x, event.y)
#print('selected:', selected) # it's not usefull
clicked_tab = nb.tk.call(nb._w, "identify", "tab", event.x, event.y)
print('clicked tab:', clicked_tab)
active_tab = nb.index(nb.select())
print(' active tab:', active_tab)
if clicked_tab == active_tab:
nb.forget(clicked_tab)
# --- main ---
root = tk.Tk()
# create notebook
nb = ttk.Notebook(root)
nb.pack(fill='both')
# bind function to notebook
nb.bind('<Button-3>', on_click)
# add some tabs
for char in "ABCDEF":
nb.add(tk.Label(nb, text=(char*15)), text=char*3)
root.mainloop()
If you remove if clicked_tab == active_tab: then you could close every tab, not only active.
来源:https://stackoverflow.com/questions/40828166/is-it-possible-to-bind-a-mouse-event-to-a-tab-of-a-notebook