Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

python - Remove tkinter text default binding

I'm making a simple tkinter Text editor, but i want all default bindings of the Text widget removed if possible.

For example when i press Ctrl + i it inserts a Tab character by default. I made an event binding that prints how many lines are in the text box, I set the event binding to Ctrl + i as well.

When i run it, It prints the number of lines inside the text box, but also inserts a tab character.

I want to know how i can Overwrite the default bindings, or learna way how to remove all the default bindings.

Heres my code btw:

from tkinter import *

class comd: # Contains primary commands
    # Capital Rule ----------------------------
    # G = Get | I = Insert | D = Draw | S = Set
    # -----------------------------------------

    def Ggeo(self): # Get Geometry (Get window geometry)
        x = root.winfo_width()
        y = root.winfo_height()
        print("Current Window Geometry")
        print(str(x) + " x " +str(y))

    def Idum(self): # Insters "Dummy Insert"
        import tkinter as tkin
        tbox.insert(INSERT, "Dummy Insert")

    def Ilim(self): # Prints How many lines are in
        info =  int(tbox.index('end-1c').split('.')[0])
        print(info)



root = Tk()
root.geometry("885x600-25-25")

tbox = Text(root, font=("Courier","14","bold"))
tbox.pack(expand = True , fill = BOTH)


# Problem here --------------------
tbox.bind("<Control-i>", comd.Ilim)
# ---------------------------------


mainloop()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can overwrite a binding by having your function return the string "break". For example:

def Ilim(self): # Prints How many lines are in
    info =  int(tbox.index('end-1c').split('.')[0])
    print(info)
    return "break"

If you want to completely remove all bindings (including the bindings that allow you to insert characters), that can be easily accomplished. All of the bindings are associated with a "bind tag" (or "bindtag"). If you remove the bindtag, you remove the bindings.

For example, this removes all of the default bindings:

    bindtags = list(tbox.bindtags())
    bindtags.remove("Text")
    tbox.bindtags(tuple(bindtags))

For more information on bind tags, see this answer: https://stackoverflow.com/a/11542200/7432


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...