Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete selected notebook tab with button tkinter

Tags:

python

tkinter

whats the function for deleting selected notebook tab in tkinter? I couldn't find anything about this on the web?

This is the code that I wrote, i only need function:

from tkinter import *
from tkinter import ttk
import math
import sys

myApp = Tk()
myApp.title(" Program ")
myApp.geometry("1000x1200")

tasktabs=ttk.Notebook(myApp)

TabOne=ttk.Frame(tasktabs)
tasktabs.add(TabOne,text="Tab One")

TabOne=ttk.Frame(tasktabs)
tasktabs.add(TabOne,text="Tab Two")

def deletetab():

    # whats the function for deleting tab?

    pass

DelButton=Button(myApp,text=' Delete  ', command=deletetab)
DelButton.grid(row=0,column=3, sticky="W")


tasktabs.grid(row=0,column=0,sticky="W")

myApp.mainloop()
like image 299
Aleksandar Beat Avatar asked Feb 11 '26 08:02

Aleksandar Beat


1 Answers

As rightly pointed by @Bryan Oakley, the above accepted answer doesn't actually "delete" the selected notebook, the object still exists but hidden from the view.

To actually delete the tab, call the .destroy() method on the child as below:

def deletetab():
    for item in tasktabs.winfo_children():
        if str(item)==tasktabs.select():
            item.destroy()       
            return  #Necessary to break or for loop can destroy all the tabs when first tab is deleted

This technique worked for me. Here's a complete sample code to test it out:

from tkinter import *
from tkinter import ttk

def deletetab():
    for item in nb.winfo_children():
        if str(item) == (nb.select()):
            item.destroy()
            return  #Necessary to break or for loop can destroy all the tabs when first tab is deleted

root = Tk()

button = ttk.Button(root,text='Delete Tab', command=deletetab)
button.pack()

nb = ttk.Notebook(root)
nb.pack()

f1 = ttk.Frame(nb)
f2 = ttk.Frame(nb)
f3 = ttk.Frame(nb)
f4 = ttk.Frame(nb)
f5 = ttk.Frame(nb)

nb.add(f1, text='FRAME_1')
nb.add(f2, text='FRAME_2')
nb.add(f3, text='FRAME_3')
nb.add(f4, text='FRAME_4')
nb.add(f5, text='FRAME_5')

root.mainloop()
like image 145
MightyInSpirit Avatar answered Feb 13 '26 00:02

MightyInSpirit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!