user7800892
user7800892

Reputation:

<Command-a> for Text - Tkinter

I found the below code :

def callback(ev):
    ev.widget.select_range(0, 'end') 

root = Tk()
t = Text(root, height=10, width=40)
t.pack()
t.bind('<Command-a>', callback) //WORKS for ENTRY
root.mainloop()

I'm basically trying to make cmd + a or Ctrl + a (Windows) work for Text in Tkinter.

Error (When I give the command : cmd-a in text):

'Text' object has no attribute 'select_range'

Upvotes: 2

Views: 937

Answers (2)

Andath
Andath

Reputation: 22714

Text class does not have select_range() function, that is why you got that error message. But you can use bind_class() to bind events to the Text class widgets. Here is a dirty demo:

import tkinter as tk

def simulate_contral_a(e):
    e.widget.tag_add("sel","1.0","end")

root = tk.Tk()
root.bind_class("Text","<Control-a>", simulate_contral_a)
T = tk.Text(root, height=2, width=30)
T.pack()
T.insert(tk.END, "Press Ctrl+a\nto select me\n")
root.mainloop()

Run this MCVE above and press Ctrl + a to see its effect:

enter image description here

Upvotes: 1

patthoyts
patthoyts

Reputation: 33193

The code is ok except that you are inventing methods on the Text widget. However, if you look at the bindings on the widget class (Text) there are some virtual events defined

>>> '<<SelectAll>>' in root.bind_class('Text')
True

So in your handler for the keyboard event, use event_generate to raise a SelectAll virtual event.

import tkinter as tk
def select_all(ev):
    ev.widget.event_generate('<<SelectAll>>')
root = tk.Tk()
txt = tk.Text(root)
txt.pack()
txt.bind('<Control-A>', select_all)

Upvotes: 3

Related Questions