我有一个关于 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/