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()
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 :)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With