【问题标题】:unremovable text in tkintertkinter 中不可删除的文本
【发布时间】:2011-10-11 11:04:21
【问题描述】:

这里有一些代码:

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 中)? 提前致谢。

【问题讨论】:

    标签: python text tkinter tk


    【解决方案1】:

    看看 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"
    

    【讨论】:

      【解决方案2】:

      没有内置的方法可以做到这一点。您将不得不设置一组覆盖默认行为的绑定,这并不是一件特别容易的事情。不过,这是可能的,因为您可以完全控制所有绑定(即:在无法更改的小部件中没有硬编码的行为)

      另一个更安全的解决方案是拦截低级 tkinter 插入和删除命令,并检查某些条件。例如,请参阅问题https://stackoverflow.com/a/11180132/7432 的答案。该答案提供了一个通用解决方案,可用于提示(如本问题所要求的),或用于将任何文本部分标记为只读。

      【讨论】:

      • +1:部分技巧是在允许更改的区域的开头有一个左重力标记,以便您可以简单地知道(通过索引比较)是否插入或删除发生在合法地点。 (Tk 控制台会这样做,所以从 Tcl 中肯定很容易,但我不知道在 Tkinter 中是如何处理的。)
      • @Donal Fellows,即使在 Tcl 中的任何简单示例都会有所帮助,谢谢。
      • @Saul:这不可能放在评论里!我可以在 8.5.10 中指向the implementation of the Tcl console,但它的代码相当多,而且大部分与你无关。
      【解决方案3】:

      IDLE 中显示的“>>>”是 Python 解释器输出的一部分。我认为您可以尝试侦听<Key> 事件并在需要时恢复提示(请参阅http://docs.python.org/library/tkinter.html#bindings-and-eventshttp://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-10
        • 1970-01-01
        相关资源
        最近更新 更多