Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Text: Setting tab spaces not working

The following code is supposed to set the number of tab spaces when is pressed to 4. The problem is it doesn't do that (it does 8 instead). I have looked on previous StackOverflow questions, and they are extremely darn vague. They describe using the getPixels function, but never expalin how to use it. Plus tkinter / tcl documentation is terrible so I am confused.

import tkinter as tk

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

def tab(arg):
    print("tab pressed")
    text.insert(tk.INSERT, " " * 4)

text.bind("<Tab>", tab)
root.mainloop()
like image 316
Henry Zhu Avatar asked Sep 21 '25 13:09

Henry Zhu


2 Answers

You are very close to what you need. All you need to do is add return 'break' to your tab(arg) function. This will keep tkinter from propagating the event further. see below

import tkinter as tk

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

def tab(arg):
    print("tab pressed")
    text.insert(tk.INSERT, " " * 4)
    return 'break'

text.bind("<Tab>", tab)
root.mainloop()

By adding the return 'break' you stop tkinter from propagating the event further. You are getting 8 spaces, because it is taking the tab and then you are adding an additional 4 spaces on top of that.

Hope this helps :)

like image 164
Joey Avatar answered Sep 23 '25 01:09

Joey


You don't need an event handler to do this, just configure the Text widget with the tab width you want:

import tkinter as tk
import tkinter.font as tkfont

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

font = tkfont.Font(font=text['font'])  # get font associated with Text widget
tab_width = font.measure(' ' * 4)  # compute desired width of tabs
text.config(tabs=(tab_width,))  # configure Text widget tab stops

root.mainloop()
like image 25
martineau Avatar answered Sep 23 '25 03:09

martineau