Select all text in a Text widget using Python 3 with tkinter

So the new code is...

from tkinter import *

# Select all the text in textbox
def select_all(event):
    textbox.tag_add(SEL, "1.0", END)
    textbox.mark_set(INSERT, "1.0")
    textbox.see(INSERT)
    return 'break'

# Open a window
mainwin = Tk()

# Create a text widget
textbox = Text(mainwin, width=40, height=10)
textbox.pack()

# Add some text
textbox.insert(INSERT, "Select some text then right click in this window")

# Add the binding
textbox.bind("<Control-Key-a>", select_all)
textbox.bind("<Control-Key-A>", select_all) # just in case caps lock is on

# Start the program
mainwin.mainloop()

and yes it works flawlessly. Thank you, very much Bryan Oakley. Steven Rumbalski: that's a VERY good point, I've followed your advice as well.


You can do that with a module named pyautogui Just run the command where you want to add the event,

import pyautogui
..., command=lambda *awargs:pyautogui.hotkey("ctrl","a")

Make sure you install the module. If you are on windows, install it by

pip install pyautogui

You need to both do the selection and then inhibit the default action by having your function return the string "break".

This is due to how Tkinter processes events. It uses what it calls "bind tags". Even though it looks like you are binding to a widget, you are actually binding to a tag that is the name of the widget. There can also be bindings to the widget class, to the toplevel window that the widget is in, and the tag "all" (plus, you can invent your own tags if you wish).

The default ordering of these tags is from most-specific to least-specific, and events are processed in that order. Meaning, if you have a binding both on the widget (most specific) and the class (less specific), the binding will fire for the widget first, and then for the class binding (and then for the toplevel, and then for "all").

What this means is that by default, a binding on a widget augments rather than replaces a default binding. The good news is, you can inhibit any further bindings from firing by simply returning the string "break", which stops the chain of bindings from doing any more work.