首页 > 解决方案 > tkinter - 如果错误未修复,如何不处理进一步的代码 - messagebox.showerror()

问题描述

我有一个 tkinter 应用程序,其中有标签、条目和按钮。每当我单击按钮时,条目都会传递给一个函数,在该函数中根据格式对其进行验证。

例如 -

两个字段 - 员工姓名、员工 ID

现在,我想检查用户名是否以“EMP”开头。为此,我做了一些功能(例如检查是否为字母数字等)。如果用户名不以“EMP”开头,我现在正在做的是显示这样的错误框

def tracking_images(self,emp_id,emp_name):
    emp_id, emp_name = emp_id.get(), emp_name.get()
    if len(emp_id) == 0:
        tk.messagebox.showerror("Field error", "Employee ID cannot be empty")
    elif len(emp_name) == 0:
        tk.messagebox.showerror("Field error", "Employee name cannot be empty")
    
    if not ValidationConditions().first_three_chars(emp_id):
        tk.messagebox.showerror("Field error", "Employee ID should start with EMP")
    ........
    ........
    #Some more code which I don't want user to have until he/she fixes the error from above checks.  <-------

现在,在用户对任何提示单击“确定”后,我不希望用户访问的代码仍然可以访问。

在修复上述检查中的错误之前,如何不让用户进一步处理?

标签: pythontkinter

解决方案


您可以以某种do-while方式处理此问题(即使 pyhton 在语义上不支持此)

伪代码如下所示:

while True:
    ask the name
    if the name passes the checks break out of the loop
    show errors

code to go to when the name is valid

编辑:我忘了注意,如下所述,这必须在一个额外的线程中完成。

另一件可能有效的事情是将对话框放在一个方法中,如果名称无效,则该方法重新开始。

但我从未尝试过,也无法测试,因为我现在正在通勤。


推荐阅读