DeathJack2.0 DeathJack2.0 - 3 years ago 131
Python Question

cmd + a not working in tkinter entry

I've being building a basic UI using Tkinter, and I noticed that cmd + a (or Select all command) is not enabled.

How do I enable all the shortcuts in tkinter especially for entry text field.

This is my code :

entry1 = ttk.Entry(root, width = 60)
entry1.pack()

Answer Source

@Goyo already answered your question. I want to share my contribution as I do not see interest in selecting the text of the Entry widget's text and not doing anything else with it. So I am going to provide you a dirty MCVE to show how you are going to use the selected text: a) either you will delete it or b) you will copy it.

For a), the following function will do the job:

def select_text_or_select_and_copy_text(e):
    e.widget.select_range(0, 'end') 

It will work under the condition you bind the corresponding events described by the function's name to the entry widget:

entry.bind('<Control-a>', select_text_or_select_and_copy_text)
entry.bind('<Control-c>', select_text_or_select_and_copy_text) 

For b), you can use this function:

def delete_text(e):
    e.widget.delete('0', 'end') 

And bind the Delete event to the entry widget:

entry.bind('<Delete>', delete_text)

I tried this MCVE on Ubuntu and it works:

import tkinter as tk
import tkinter.ttk as ttk


def select_text_or_select_and_copy_text(e):
    e.widget.select_range(0, 'end')     

def delete_text(e):
    e.widget.delete('0', 'end')


root = tk.Tk()

entry = ttk.Entry(root)
entry.pack()

entry.bind('<Control-a>', select_text_or_select_and_copy_text)
entry.bind('<Control-c>', select_text_or_select_and_copy_text)
entry.bind('<Delete>', delete_text)

root.mainloop()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download