Search code examples
pythontkinterkey

make Tab key do 4 space instead 8 in textbox tkinter


I'm trying to create a text editor with tkinter When I click on the Tab key on the keyboard it does 8 spaces I want it to do only 4 spaces instead of 8 code:

import tkinter as tk

root = tk.Tk()
root.title('Text editor')

text = tk.Text(root)
text.pack()


root.mainloop()

Solution

  • Try this:

    import tkinter as tk
    
    def tab_pressed(event:tk.Event) -> str:
        # Insert the 4 spaces
        text.insert("insert", " "*4)
        # Prevent the default tkinter behaviour
        return "break"
    
    root = tk.Tk()
    
    text = tk.Text(root)
    text.pack()
    text.bind("<Tab>", tab_pressed)
    
    root.mainloop()
    

    I used .bind and return "break" to add my own functionality for when the tab key is pressed while blocking tkinter's default behaviour.

    If you just want the tabs to be 4 spaces wide, look here.