【问题标题】:Tkinter widget validation issue - againTkinter 小部件验证问题 - 再次
【发布时间】: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


【解决方案1】:

错误表明您正在尝试将空字符串转换为整数。只有一行代码您正在执行此操作,因此错误的位置非常清楚。您只需在尝试将user_input 转换为整数之前检查空字符串。或者捕获此特定错误并返回False,假设空字符串无效。

部分根本原因是由于您的参数向后设置。您按此顺序传入%P(新值)和%S(插入或删除的文本),但您的函数具有名为user_inputnew_value 的参数。因此,%P 映射到 user_input%S 映射到 new_value

【讨论】:

  • 是的,我修复了向后的参数。那只是我的疏忽,哎呀。是的,如果我在进行 len 和范围检查之前再检查一次 '',它会起作用!谢谢你,Bryan,你是少数 :) 用户将无法选择旋转框中的整数然后输入一个新值(因为在新字符被放在那里之前,这必然会使旋转框完全为空,这打破验证)......但我认为这没什么大不了的。我宁愿始终拥有安全的价值观。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多