.register()
函数注册,以便它可以成为一个回调函数。
以下是我发现的内容:Tkinter 8.5 reference
所以它应该是这样的:
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = EntryBoxFormated()
self.entry.pack()
class EntryBoxFormated (tk.Entry):
def __init__ (self, min=None, max=None, precision=None, type=None):
if (min == None):
self.min = 0
if (max == None):
self.max = 10
if (precision == None):
self.precision = 4
if (type == None or type != 'string'):
self.type = "float"
self.entryTkValue = self.initEntryValue()
cmd = self.register(self.entryFloatValidation)
super().__init__(textvariable = self.entryTkValue, text = self.entryTkValue, validate=tk.ALL, validatecommand = cmd)
def initEntryValue(self):
initVal = "0"
if (self.precision > 0):
initVal += "."
for i in range(0,self.precision):
initVal += "0"
return tk.StringVar(value=initVal)
def entryFloatValidation(self):
tempString = self.entryTkValue.get()
n = len(tempString)
nbPoints = 0
res = True
i=0
while (i<n):
if (tempString[i] < '0' or tempString[i] > '9'):
if (tempString[i] == ',' or tempString[i] == ';'):
tempString[i] == '.'
if (tempString[i] == '.'):
nbPoints += 1
if (nbPoints > 1):
res = False
else:
res = False
if (res):
if (float(tempString) < self.min or float(tempString) > self.max):
res = False
else:
self.delete(0,tk.END)
self.insert(0,tempString)
return res
if (__name__ == '__main__'):
window = Window()
window.mainloop()
window.quit()
但是有了这个,我收到了这个错误:
Traceback (most recent call last): File
"/home/aubin/PyzoWorkspace/Interface/TESTS/topic.py", line 75, in
<module>
window = Window() File "/home/aubin/PyzoWorkspace/Interface/TESTS/topic.py", line 9, in
__init__
self.entry = EntryBoxFormated() File "/home/aubin/PyzoWorkspace/Interface/TESTS/topic.py", line 28, in
__init__
cmd = self.register(self.entryFloatValidation) File "/home/aubin/anaconda3/lib/python3.6/tkinter/__init__.py", line 1366,
in _register
self.tk.createcommand(name, f) AttributeError: 'EntryBoxFormated' object has no attribute 'tk'
如果我跳过在EntryBoxFormated类的init()中注册的调用,我没有得到任何错误,但窗口没有显示。
我在伪造什么吗?
提前致谢。
编辑: 有办法绕过那个吗?我认为以下行但它没有(没有错误,但窗口没有出现)
super().__init__(textvariable = self.entryTkValue, text = self.entryTkValue, validate=tk.ALL)
cmd = self.register(self.entryFloatValidation)
self.configure(validatecommand=cmd)