【问题标题】:messagebox stops validation消息框停止验证
【发布时间】:2023-04-09 03:26:01
【问题描述】:

我不明白为什么消息框(或 simpledialog)会破坏以下代码的流程。该代码基本上验证了 python 3.5 中的输入框。它检查该字段是否仅包含数值并且它的长度不超过 9 位,但输入框可以为空。向用户添加一条消息,在他们确定之后,允许输入框超过 9 位并接受字母,这当然是我不希望这样做的。

from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
root = Tk()


root.title("Zebra")
root.update_idletasks()
root.geometry("350x200+600+300")
root.config(bg="blue")

def okay(old,new): #,c,d,e,f,g,h):

    try:
        x = int(new)
    except ValueError as ex:
        if len(new) == 0:
            return True
        else:
            return False
    else:

        if len(new) > 9:
            messagebox.showerror("Error","Entry is too long")
           # When messagebox is removed or commented out all is working ok
           # but add below line and BINGO it works again :-)

            txtNorm.config(validate='all', vcmd=vcmd) 
           # New line above as of 08/03/2016 brings validation back.
            return False

        elif len(new) <=9:
            return True
    finally:

        if len(new) > 9:

            return False


        pass
def txtNormToggle(event): # When the user double clicks the field to enter or correct a number.
    txtNorm.config(state="normal")
def txtNormFinished(a):
    txtNorm.config(state="disabled")
    root.focus()

vcmd=(root.register(okay),'%s','%P')


txtNorm = Entry(root)
txtNorm.grid(row=1, column=1,padx=(15,15),pady=(15,15), sticky=E+W)
txtNorm.insert(0,"123")
txtNorm.config(state="disabled", justify="center", validate='all', vcmd=vcmd)
txtNorm.bind('<Button>',txtNormToggle)
txtNorm.bind('<Control-z>',txtNormFinished)
txtNorm.bind('<Escape>',txtNormFinished)
txtNorm.bind('<Return>',txtNormFinished)


root.mainloop()

上面没有消息框会阻止用户输入除我想要的数字以外的任何内容,一旦单击“确定”,带有消息框的输入字段允许超过 9 个数字和其他字符

编辑:好的,所以我创建了自己的弹出子窗口并且验证仍然在窗口之外,怀疑这与主窗口失去焦点有关,从输入框中杀死验证。请有任何想法。

【问题讨论】:

  • 你是怎么调用那个函数的?您使用的是哪个 GUI 框架?是 Tkinter 吗?
  • 嘿 PM - 我正在使用 tkinter。我已将对函数的调用包装为; codevcmd=(root.register(okay),'%s','%P')
  • 更新了原始问题 - 我认为这可能是失去焦点的事情 {:-{ 但不知道为什么??
  • 您可能需要给我们一个minimal reproducible example,以便我们尝试重现此问题。
  • 您好 PM - 上面的代码现在是完整的代码,对不起,我应该首先发布它的全部内容。如果您能指出这个问题的正确方向,请提前感谢您的宝贵时间。

标签: python python-3.x tkinter messagebox simpledialog


【解决方案1】:

我已将 validate 添加回 (okay) 函数的输入框中,但它并没有向我解释为什么会发生验证丢失。代码现在按我想要的方式工作

【讨论】:

    猜你喜欢
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    相关资源
    最近更新 更多