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 中)? 提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看一下IDLE的源代码。特别是查看 EditorWindow.py 中的“smart_backspace_event”。 IDLE 将文本小部件上的
绑定到此函数(间接通过<>
事件)。您需要的基本代码如下所示:
Take a look at IDLE's source code. In particular look at 'smart_backspace_event' in EditorWindow.py. IDLE binds
<Key-Backspace>
on the text widget to this function (indirectly through the<<smart-backspace>>
event).The basic code you'll need follows like this:
没有内置的方法可以做到这一点。您必须设置一组覆盖默认行为的绑定,这并不是一件特别容易的事情。不过,这是可能的,因为您可以完全控制所有绑定(即:在无法更改的小部件中没有硬编码任何行为)
另一个更防弹的解决方案是拦截低级 tkinter 插入和删除命令,并检查某些条件。例如,请参阅问题的答案 https://stackoverflow.com/a/11180132/7432。该答案提供了一个通用解决方案,可用于提示(如本问题中所要求的),或将文本的任何部分标记为只读。
There is no built in way to do this. You will have to set up a collection of bindings that override the default behavior, and that's not a particularly easy thing to do. It's possible, though, since you have complete control over all bindings (ie: no behavior is hard-coded in the widget where it can't be changed)
Another solution which is more bullet proof is to intercept the low-level tkinter insert and delete commands, and check for some condition. For an example, see the answer to the question https://stackoverflow.com/a/11180132/7432. That answer provides a general solution that can be used for a prompt (as asked for in this question), or for tagging any sections of text as readonly.
'>>>' IDLE 中显示的是 Python 解释器输出的一部分。我认为您可以尝试侦听
事件并在需要时恢复提示(请参阅 http://docs.python.org/library/tkinter.html#bindings-and-events 和 http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm)The '>>>' displayed in IDLE is a part of Python interpreter output. I think you can try listening for
<Key>
events and restoring the prompt when needed (see http://docs.python.org/library/tkinter.html#bindings-and-events and http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm)