【发布时间】:2015-08-24 18:00:54
【问题描述】:
与我有here 的一个已经回答的问题相关,我仍然无法弄清楚如何解决验证,以便它在任何情况下都不会中断。目前,大多数情况下它运行良好,除非您选择值然后输入一些输入。
示例:加载程序,选择微调框 (8) 中的数字,然后键入任意数字。即使数字仍在控制范围内 (1-128),它也会使用 ValueError: invalid literal for int() with base 10: '' 破坏验证。
有什么想法吗?
try:
from Tkinter import *
except ImportError:
from tkinter import *
class GUI:
def __init__(self):
# root window of the whole program
self.root = Tk()
self.root.title('ImageSound')
# registering validation command
vldt_ifnum_cmd = (self.root.register(self.ValidateIfNum),'%P', '%S', '%W')
# creating a spinbox
harm_count = Spinbox(self.root, from_=1, to=128, width=5, justify='right', validate='all', validatecommand=vldt_ifnum_cmd)
harm_count.insert(0,8)
harm_count.delete(1,'end')
harm_count.pack(padx=10, pady=10)
def ValidateIfNum(self, user_input, new_value, widget_name):
# disallow anything but numbers in the input
valid = new_value == '' or new_value.isdigit()
# now that we've ensured the input is only integers, range checking!
if valid:
# get minimum and maximum values of the widget to be validated
minval = int(self.root.nametowidget(widget_name).config('from')[4])
maxval = int(self.root.nametowidget(widget_name).config('to')[4])
# check if it's in range
if int(user_input) not in range (minval, maxval):
valid = False
if not valid:
self.root.bell()
return valid
if __name__ == '__main__':
mainwindow = GUI()
mainloop()
【问题讨论】:
-
能否请您添加完整的回溯?
标签: python validation tkinter