Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmd + a not working in tkinter entry

Tags:

python

tkinter

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()
like image 732
DeathJack Avatar asked Jan 29 '23 22:01

DeathJack


2 Answers

If tkinter doesn't define the shorcuts you want you can define your own by binding keyboard events.

import tkinter as tk
import tkinter.ttk as ttk

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

root = tk.Tk()
entry = ttk.Entry(root)
entry.pack()
entry.bind('<Command-a>', callback)
root.mainloop()

I think Command is the correct prefix for the cmd key but I don't have a mac to test. In windows it binds to the control key.

like image 133
Stop harming Monica Avatar answered Feb 02 '23 10:02

Stop harming Monica


@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()
like image 29
Billal Begueradj Avatar answered Feb 02 '23 11:02

Billal Begueradj