Reputation: 1045
I would like to enable ctrl+a to select the text within a combobox. Instead of selecting all it does <end> (more or less at least).
minimal example:
#!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
root = tk.Tk()
def month_changed(event):
msg = f'You selected {month_cb.get()}!'
showinfo(title='Result', message=msg)
# month of year
months = ['Jan', 'Feb']
# create a combobox
selected_month = tk.StringVar()
month_cb = ttk.Combobox(root, textvariable=selected_month)
month_cb['values'] = months
month_cb.pack(fill='x', padx=5, pady=5)
month_cb.bind('<<ComboboxSelected>>', month_changed)
month_cb.bind('<Control-a>', doSomeSelecting) #doSomeSelcting tbd
root.mainloop()
I stole the example and minimized it from here to get a quick example: https://www.pythontutorial.net/tkinter/tkinter-combobox/
Upvotes: 2
Views: 220
Reputation: 33193
So what you are doing is overriding the default bindings for your platform. On X11 Tk sets up a default binding for Control-Key-slash
to generate the <<SelectAll>>
virtual event. On Win32 this is extended with Control-Key-a
as well. On X11 Control-a is bound to <<LineStart>>
.
So the platfrom correct thing is to leave it alone and learn to use Control-slash to select all. To override this you need to bind Control-a to a function that generates the SelectAll virtual event and also prevents the default event handler from then moving the insertion point to the start of the line. For that:
def selall(ev):
ev.widget.event_generate('<<SelectAll>>')
return 'break'
month_cb.bind('<Control-a>', selall)
The return 'break'
is important here otherwise the event handlers will continue being called and our selection will be undone when something generates the <<LineStart>>
event after our <<SelectAll>>
.
This can be investigated in IDLE using month_cb.bindtags()
to find that it's class bindings are TCombobox. Then month_cb.bind_class('TCombobox')
to see all the events that are bound to this class. For the virtual events, root.event_info('<<SelectAll>>')
shows the set of events that cause this virtual event to be raised.
Upvotes: 1