我正在嘗試創建一個具有非常特殊驗證的條目。為此,我正在玩弄 validatecommand。但是,我遇到了一個問題:
當條目中的某些內容被洗掉時,我無法判斷它是使用洗掉鍵還是退格鍵完成的(以及這樣的教程頁面:https ://www.pythontutorial.net/tkinter/tkinter-validation/沒有指示替換提供該資訊)。
所以,我決定添加一個系結。我鏈接的函式回傳“break”,并且必須注意洗掉一個字符并在其位置插入一個空格。
正如標題所說,問題在于 validatecommand 甚至可以驗證使用 insert 和 delete 方法所做的條目編輯。
為避免這種情況,我考慮在進行相應編輯時禁用驗證(始終回傳 True)。但這可能會導致其他條目無法驗證。
以編程方式編輯條目時,有沒有辦法跳過該驗證?
我把這段代碼留給你,以便你有一些基礎來幫助我:
from functools import partial
class ChrFormat:
def __init__(self):
self.charvalidators = []
def register_in(self, widget):
widget.config(validate="key", validatecommand=(widget.register(partial(self, widget)), "%d", "%i", "%P", "%s", "%S"))
def add(self, obj):
self.charvalidators.append(obj)
def __call__(self, widget, accion, index, new_text, old_text, char):
accion = int(accion)
index = int(index)
if(len(char) == 1):
if(accion == 1):
if(index < self.width):
for validator in self.charvalidators[index:]:
if(not isinstance(validator, str)):
break
index = 1
else:
return False
if(validator(char)):
widget.delete(index)
widget.insert(index, char)
widget.icursor(index 1)
return (accion != 1)
def apply(self):
self.width = len(self.charvalidators)
self.null = "".join((part if(isinstance(part, str)) else " ") for part in self.charvalidators)
fecha = ChrFormat()
fecha.add(str.isdecimal)
fecha.add(str.isdecimal)
fecha.add("-")
fecha.add(str.isdecimal)
fecha.add(str.isdecimal)
fecha.add("-")
fecha.add(str.isdecimal)
fecha.add(str.isdecimal)
fecha.add(str.isdecimal)
fecha.add(str.isdecimal)
fecha.apply()
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
sv = tk.StringVar()
entrada = ttk.Entry(textvariable=sv)
entrada.pack()
fecha.register_in(entrada)
sv.set(fecha.null)
我想我沒有很好地解釋自己,對不起。我正在尋找的是,當用戶按下退格鍵時,它會洗掉一個數字并在其位置放置一個空格。和洗掉類似的東西。但我需要知道將那個空間放在游標的哪一側。
顯然,自然驗證是正確的,也許通過系結進行驗證。
對于那些稍微了解 Clipper 編程語言的人,我想模仿放置圖片時發生的情況,例如'@r 999.999'. 我會發布一個視頻,但我不是在錄制的好時機,我沒有找到任何視頻來證明這一點。
uj5u.com熱心網友回復:
以編程方式編輯條目時,有沒有辦法跳過該驗證?
最簡單的解決方案是validate在進行編輯之前將選項設定為“無”。after_idle然后,您可以按照官方 tk 檔案中的說明重新打開驗證
widget.configure(validate="none")
widget.delete(index)
widget.insert(index, char)
widget.icursor(index 1)
widget.after_idle(lambda: widget.configure(validate="key"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475169.html
