5

Does anyone know how to trigger a function once a different tab is selected in the tkinter notebook?

This is hat i what to accomplish.

Lets say i have two tabs, tab1 and tab2:

if tab1 is selected:
    canvas3.unbind_all() 
    canvas2.bind_all('<MouseWheel>', lambda event: canvas2.yview_scroll(int(-1 * (event.delta / 120)),"units"))

elif tab 2 is selected:
    canvas2.unbind_all()
    canvas3.bind_all('<MouseWheel>', lambda event: canvas3.yview_scroll(int(-1 * (event.delta / 120)), "units"))
3
  • 1
    You can bind <<NotebookTabChanged>> event. Commented Feb 12, 2020 at 12:25
  • could you explain how would you do it please? Commented Feb 12, 2020 at 13:10
  • @IgnacioBares The '<MouseWheel>' event are selective by which widget are in mouse focus. Relevant binding mousewheel to scrollbar Commented Feb 12, 2020 at 13:11

1 Answer 1

11

You can bind <<NotebookTabChanged>> event on the notebook:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

nb = ttk.Notebook(root, width=800, height=600)
nb.pack()

frame1 = ttk.Frame(nb)
frame2 = ttk.Frame(nb)

nb.add(frame1, text='Tab1')
nb.add(frame2, text='Tab2')

def on_tab_change(event):
  tab = event.widget.tab('current')['text']
  if tab == 'Tab1':
    #canvas3.unbind_all() 
    #canvas2.bind_all('<MouseWheel>', lambda event: canvas2.yview_scroll(int(-1 * (event.delta / 120)),"units"))
  elif tab == 'Tab2':
    #canvas2.unbind_all()
    #canvas3.bind_all('<MouseWheel>', lambda event: canvas3.yview_scroll(int(-1 * (event.delta / 120)), "units"))

nb.bind('<<NotebookTabChanged>>', on_tab_change)

root.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly! Just needed to erase the unbind_all() part and it worked without errors :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.