开发者

unremovable text in tkinter

开发者 https://www.devze.com 2023-04-12 09:41 出处:网络
here is some code: from Tkinter import * class Main(object): def __init__(self): self.console = Text(root, relief=\'groove\', cursor=\'arrow\', spacing1=3)

here is some code:

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

is there some way to make '>>> ' become unremovable(like in IDLE for example)? thanks in advance.


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:

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"


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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消