组合框启用 ctrl+a 选择文本 [英] Combobox enable ctrl+a to select text

查看:33
本文介绍了组合框启用 ctrl+a 选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启用 ctrl+a 来选择组合框中的文本.而不是选择所有它做 <end>(至少或多或少).

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).

最小示例:

#!/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()

我从这里窃取了示例并将其最小化以获得一个快速示例:https://www.pythontutorial.net/tkinter/tkinter-combobox/

I stole the example and minimized it from here to get a quick example: https://www.pythontutorial.net/tkinter/tkinter-combobox/

推荐答案

所以您正在做的是覆盖您平台的默认绑定.在 X11 上,Tk 为 Control-Key-slash 设置默认绑定以生成 <> 虚拟事件.在 Win32 上,这也通过 Control-Key-a 进行了扩展.在 X11 上,Control-a 绑定到 <>.

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>>.

所以平台正确的做法是不要管它,学会使用Control-slash全选.要覆盖它,您需要将 Control-a 绑定到一个生成 SelectAll 虚拟事件的函数,阻止默认事件处理程序将插入点移动到行的开头.为此:

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)

return 'break' 在这里很重要,否则事件处理程序将继续被调用,并且当某些东西生成 < <> 之后的事件.

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>>.

这可以在 IDLE 中使用 month_cb.bindtags() 进行调查,以发现它的类绑定是 TCombobox.然后month_cb.bind_class('TCombobox') 查看绑定到这个类的所有事件.对于虚拟事件,root.event_info('<<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.

这篇关于组合框启用 ctrl+a 选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆