python-3.x - 如何在 tkinter 中使特定文本不可删除?

标签 python-3.x tkinter

我有一个关于 Tkinter 文本和条目小部件的快速问题。 如何使特定文本不可删除? 是的,我知道 .config(state="disabled") 不,这不是我想要的,它只是使所有文本都不可移动。

假设我有一个文本框。在该文本框中有一个“输入消息”文本。 用户可以像任何其他文本框一样键入和删除。但是,我不希望用户删除“输入消息”。

就像在 Windows shell 中你不能删除 "C:\Users\your username>" 或您所在的任何目录。

这里有一些代码:

from tkinter import *

root = Tk()
root.geometry("500x500")
entry = Entry(root, bg="black", fg="white")
entry.pack(side="top", fill="x")
entry.insert(END, "Enter message: ")
entry.non_removable("Enter message: ") # << not a real code. just what i imagine it to be

mainloop()

最佳答案

另一种方法是使用验证。

def do_validate( text ):
    # if this returns False the entered key(s) aren't accepted.
    return text.startswith( "Enter message: " )

import tkinter as tk

root = tk.Tk()
root.geometry("500x500")
entry = tk.Entry(root, bg="black", fg="white")
entry.pack(side="top", fill="x")
entry.insert( tk.END, "Enter message: ")

validate_cmd = ( root.register( do_validate ), '%P' )
entry.config( validate = 'key', validatecommand = validate_cmd )

root.mainloop()

如果按键创建的字符串不是以“Enter Message:”开头,则按键被拒绝并且条目文本不变。

关于python-3.x - 如何在 tkinter 中使特定文本不可删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65521815/

相关文章:

python - 在 Python 3 中不使用 `break` 停止迭代

python - 小狗。如何动态更改顶点的图片(动画)。 OpenGL

Python html 字母表

python - 将焦点上的 tkinter 标签文本斜体化

image - 如何使用 tkinter/ttk 在 Python 3 中显示图像?

python - Tkinter Optionmenu StringVar.get() 返回空白

python - 在列表上使用remove()后"TypeError: object of type ' NoneType ' has no len()"

python - Twofish key 扩展

python - 将文本应用到两个 tkinter RadioButton

python - 是否可以获取 tkinter 文本中标记的数字索引(位置)?