当我复制一些文本并将其粘贴(ctrl + v)到 tkinter Entry 中时,如果有选定的文本,它不会将其从条目中删除。我使用的是 Linux (Mint) 64 位。
Here I copy "d" with (ctrl + c):
Then I select "b":
Now I paste "d" (ctrl + v) onto it but the result is this:
First:我想知道这是 Linux 特有的错误还是本来就是这样的?
Second:我正在考虑解决这个问题的方法validatecommand
但我遇到了另一个问题:
如果我要删除命令中选定的文本,我必须知道条目中选择的索引。否则,如果在光标之后和之前有多个选定文本的实例,我将不知道要删除哪一个并用新文本替换。因为光标可能位于所选内容的任一侧(取决于用户是否在文本上从右到左或从左到右拖动鼠标)。
现在有没有办法获得index of 选择在条目中?或者另一种方法来解决这个问题?
这是一些带有问题示例的代码:
import tkinter as tk
root = tk.Tk()
def validation(after_text, before_text, validation_text, cursor_index):
cursor_index = int(cursor_index)
print('cursor index:', cursor_index)
print('text after change:', after_text)
print('text before change:', before_text)
print('text in need of validation:', validation_text)
try:
selection = root.selection_get()
except:
selection = ''
print('selection:', selection)
# EXAMPLE:
# validation_text = 'd'
# before text = "bb"
# now if someone dragged from right to left on the 2nd b:
# cursor position will be 1 (imagine | as the cursor): 'b|b'
# cursor_index = 1
# after_text = 'bdb' --> but should be 'bd'
# now if someone dragged from left to right on the 2nd b:
# cursor position will be 2 (imagine | as the cursor): 'bb|'
# cursor_index = 2
# after_text = 'bbd' --> but should be 'bd'
# so there is no way for me to know which of these b's I have
# to replace with d based on cursor position alone. I have to
# know the index of selection itself in before_text to be
# able to replace the text properly.
# I don't know how to get that.
return True
txtvar = tk.StringVar(value = 'a-b-c-d-e')
entry = tk.Entry(root, textvariable = txtvar)
font = tk.font.Font(family = entry.cget('font'), size = -50)
entry.config(validate = 'all',
vcmd = (root.register(validation),'%P', '%s', '%S', '%i'),
font = font)
entry.pack()
root.mainloop()