在tkinter中无法删除的文本
这里有一些代码:
from Tkinter import *
class Main(object):
def __init__(self):
self.console = Text(root, relief='groove', cursor='arrow', spacing1=3)
self.console.insert(INSERT, '>>> ')
self.console.focus_set()
self.scroll = Scrollbar(root, cursor='arrow', command=self.console.yview)
self.console.configure(yscrollcommand=self.scroll.set)
self.scroll.pack(fill='y', side='right')
self.console.pack(expand=True, fill='both')
root = Tk()
root.geometry('%sx%s+%s+%s' %(660, 400, 40, 40))
root.option_add('*font', ('Courier', 9, 'bold'))
root.resizable(0, 1)
app = Main()
root.mainloop()
有没有办法让'>>> '这个符号变得不可删除(就像在IDLE里那样)?谢谢!
3 个回答
3
这个功能没有现成的方法可以实现。你需要设置一系列的绑定来覆盖默认的行为,这并不是一件简单的事情。不过,这也是可以做到的,因为你可以完全控制所有的绑定(也就是说,组件里的行为没有硬编码,都是可以更改的)。
另一个更可靠的解决方案是拦截底层的tkinter插入和删除命令,然后检查一些条件。想要了解具体的例子,可以看看这个问题的回答:https://stackoverflow.com/a/11180132/7432。这个回答提供了一个通用的解决方案,可以用来处理提示(正如这个问题所要求的),或者将任何文本部分标记为只读。
3
看看IDLE的源代码,特别是EditorWindow.py文件里的'smart_backspace_event'这个部分。IDLE把文本框里的<Key-Backspace>
这个按键绑定到了这个函数上(其实是通过<<smart-backspace>>
这个事件间接绑定的)。
你需要的基本代码大致如下:
chars = console.get("insert linestart", "insert")
# [Do some analysis on "chars" to detect >>> and prevent a backspace]
if DO_BACKSPACE:
console.delete("insert-1c", "insert")
# "break" is important so that the Text widget's backspace handler doesn't get called
return "break"