我一直在尝试将一些验证集成到文本输入字段中。
我找到了一个非常有用的帖子here,由用户unbutu创建了一个只能接受字符的文本输入字段:`0123456789。+ - ]。然后我尝试解构代码示例,以便更好地理解它是如何工作的。
我的缩减代码如下,但有几个部分我仍然感到困惑。如果有人能借助他们的智慧来帮助我理解,那我真的很感激。
import tkinter as tk
# Create root window
root = tk.Tk()
class entryWithValidation:
def __init__(self, parent):
# Calls the validationFunc function? Why no parenthesis? How do arguments get
# passed to the function?
checkFunc = self.validationFunc
# note 1
registeredCheckFunc = parent.register(checkFunc)
# As far as I can tell, this is just a tuple to improve readability.
# The whole tuple needs to be passed as a single argument to 'validatecommand'
shortcut = (registeredCheckFunc,'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
# creates an entry widget, within 'root', that runs the validation command
# whenever a key is pressed. The validation command is 'shortcut'
self.textEntry = tk.Entry(root,
validate = 'key',
validatecommand = shortcut)
# Packs entry like normal
self.textEntry.pack()
# What are all the arguments for? They don't seem to get used anywhere
def validationFunc(self, action, index, value_if_allowed,
prior_value, text, validation_type,
trigger_type, widget_name):
# However the 'text' argument is passed to this function,
# it checks the character against the string of valid characters provided,
# and returns true if present, false if not.
if text in '0123456789':
return True
else:
return False
entryWithValidation(root)
root.mainloop()
注1:我已经在effbot阅读了文档,但说实话,我无法做出正面或反面。 Tcl包装程序? Python回调?什么?