Reputation: 143
I wanted to bind 'Enter' key to only one of the tab, here's the sample code
from tkinter import *
from tkinter import ttk
def hello(event):
print('hello')
window = Tk()
window.geometry('500x500')
tab_control = ttk.Notebook(window)
tab_1 = ttk.Frame(tab_control)
tab_2 = ttk.Frame(tab_control)
tab_control.add(tab_1, text='Tab 1')
tab_control.add(tab_2, text='Tab 2')
tab_control.pack(expand=1, fill='both')
window.bind('<Return>', hello)
window.mainloop()
window.bind()
will allow the user to run hello()
function in both tabs. But I only wish to bind it to tab_1
.
I tried tab_1.bind('<Return>', hello)
but there's no response at all in both tab.
Upvotes: 0
Views: 453
Reputation: 344
You can use the select()
method of Notebook
in tkinter. Here's an example:
Suppose you have a notebook with 2 frames in it. And no matter what happens, when you press the Return
key in your keyboard, the focus should be one the first frame then use this:
name_of_notebook.select(0)
Here 0 is like the index number as it starts at zero.
Note: When setting keybinds, make sure to bind them right to the widget in which a change should happen
Upvotes: 0
Reputation: 12672
Use <<NotebookTabChanged>>
event to get the active tab,then bind event for your app:
from tkinter import *
from tkinter import ttk
def hello(event=None):
print("hello")
def e(event=None):
if tab_control.index(tab_control.select()) == 0: # bind event for the first tab.
window.bind("<Return>", hello)
else:
window.unbind("<Return>")
window = Tk()
window.geometry('500x500')
tab_control = ttk.Notebook(window)
tab_1 = ttk.Frame(tab_control)
tab_2 = ttk.Frame(tab_control)
tab_control.add(tab_1, text='Tab 1')
tab_control.add(tab_2, text='Tab 2')
tab_control.pack(expand=1, fill='both')
window.bind('<<NotebookTabChanged>>', e)
window.mainloop()
Upvotes: 5