Python - 如果输入字段为空,则显示messagebox

时间:2017-03-13 19:22:10

标签: python class validation messagebox

我遇到了这个问题,如果输入字段为空,我希望我的程序显示一个messageebox。单击按钮时会运行该功能,它将从frame类的输入字段中获取所有数据,并将它们放入电子表格文件中。所有输入字段都存储在另一个函数中。我还有另一个名为emailframe的班级。这是按钮功能的代码:

def getVal(self):
    try:
        path = str(tm.strftime("%d-%m-%Y")) + ' - ' + str(tm.strftime("%A")) + '.xlsx'

        wb = xl.load_workbook(path)
        ws = wb.active

        entry_list = [child for child in root.winfo_children()
                      if isinstance(child, tk.Entry)]

        for entry in entry_list:
            if not entry.get():
                msgbox.showinfo('Daily Accounts', 'Enter in to entry fields.')
            else:
                ws['B3'] = float(self.entryBags.get())
                ws['B4'] = float(self.entryNotes.get())
                ws['B5'] = float(self.entry2pound.get())
                ws['B6'] = float(self.entry1pound.get())
                ws['B7'] = float(self.entry50p.get())
                ws['B8'] = float(self.entry20p.get())
                ws['B9'] = float(self.entry10p.get())
                ws['B10'] = float(self.entry5p.get())
                ws['B11'] = float(self.entry2p.get())
                ws['B12'] = float(self.entry1p.get())
                ws['B14'] = float(self.entryPrevTill.get())
                ws['B16'] = float(self.entryCard.get())
                ws['B17'] = float(self.entryCash.get())

        wb.save(path)

        app = xw.App(visible = False)
        book = xw.Book(path)
        ws2 = book.sheets[0]

        total_till = str(ws2.range('B13').value)
        till = str(ws2.range('B15').value)
        day_total = str(ws2.range('B18').value)

        self.lblTotalTillDisplay.configure(text = '£' + total_till) 
        self.lblLeftTillDisplay.configure(text = '£' + till)
        self.lbldaytotal2.configure(text = '£' + day_total)

        msgbox.showinfo('', 'Data Submitted.')

        book.close()
        app.kill()

    except IOError:
        msgbox.showinfo('Daily Accounts', 'New Day has not been created.')

我尝试使用winfo_children函数获取所有输入字段,但我不确定它是否有效,因为我在另一个类中有其他输入字段,我不想检索。

这是我剩下的代码的主要部分:

class frame(tk.Frame):
def __init__(self, master):
    self.frame = ttk.Frame(master)
    self.frame.pack(fill="both", expand = True)

    self.entryfields()
    self.buttons()

def entryfields(self):  

    vcmd = (self.frame.register(self.validate),     
            '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')

    self.entryBags = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd) 
    self.entryBags.place(x = 100, y = 40)        
    self.entryNotes = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entryNotes.place(x = 100, y = 60)
    self.entry2pound = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry2pound.place(x = 100, y = 80)
    self.entry1pound = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry1pound.place(x = 100, y = 100)
    self.entry50p = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry50p.place(x = 100, y = 120)
    self.entry20p = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry20p.place(x = 100, y = 140)
    self.entry10p = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry10p.place(x = 100, y = 160)
    self.entry5p = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry5p.place(x = 100, y = 180)
    self.entry2p = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry2p.place(x = 100, y = 200)
    self.entry1p = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entry1p.place(x = 100, y = 220)
    self.entryPrevTill = tk.Entry(self.frame)
    self.entryPrevTill.place(x = 100, y = 260)
    self.entryPrevTill.insert(0, 100)           
    self.entryCard = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)       
    self.entryCard.place(x = 100, y = 300)
    self.entryCash = tk.Entry(self.frame, validate = 'key', validatecommand = vcmd)
    self.entryCash.place(x = 100, y = 320)

def validate(self, action, index, value_if_allowed,
    prior_value, text, validation_type, trigger_type, widget_name):
    if(action=='1'):
        if text in '0123456789.':
            try:
                float(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
    else:
        return True

def buttons(self):
    self.btnSub = tk.Button(self.frame, text = 'Submit', width = 30, command = self.getVal)
    self.btnSub.place(x = 20, y = 340)

def getVal(self):
    try:
        path = str(tm.strftime("%d-%m-%Y")) + ' - ' + str(tm.strftime("%A")) + '.xlsx'

        wb = xl.load_workbook(path)
        ws = wb.active

        entry_list = [child for child in root.winfo_children()
                      if isinstance(child, tk.Entry)]

        for entry in entry_list:
            if not entry.get():
                msgbox.showinfo('Daily Accounts', 'New Day has not been created.')
            else:
                ws['B3'] = float(self.entryBags.get())
                ws['B4'] = float(self.entryNotes.get())
                ws['B5'] = float(self.entry2pound.get())
                ws['B6'] = float(self.entry1pound.get())
                ws['B7'] = float(self.entry50p.get())
                ws['B8'] = float(self.entry20p.get())
                ws['B9'] = float(self.entry10p.get())
                ws['B10'] = float(self.entry5p.get())
                ws['B11'] = float(self.entry2p.get())
                ws['B12'] = float(self.entry1p.get())
                ws['B14'] = float(self.entryPrevTill.get())
                ws['B16'] = float(self.entryCard.get())
                ws['B17'] = float(self.entryCash.get())

        wb.save(path)

        app = xw.App(visible = False)
        book = xw.Book(path)
        ws2 = book.sheets[0]

        total_till = str(ws2.range('B13').value)
        till = str(ws2.range('B15').value)
        day_total = str(ws2.range('B18').value)

        self.lblTotalTillDisplay.configure(text = '£' + total_till) 
        self.lblLeftTillDisplay.configure(text = '£' + till)
        self.lbldaytotal2.configure(text = '£' + day_total)

        msgbox.showinfo('', 'Data Submitted.')

        book.close()
        app.kill()

    except IOError:
        msgbox.showinfo('Daily Accounts', 'New Day has not been created.')

def email(self):
    self.frame.destroy()
    app = emailFrame(root)

class emailFrame(tk.Frame):
def __init__(self, master):
    self.eframe = ttk.Frame(master)
    self.eframe.pack(fill="both", expand = True)

    self.entry()

def entry(self):

    self.entryemail = tk.Entry(self.eframe, width = 40)
    self.entryemail.place(x = 180, y = 20)

if __name__ == "__main__":
root = tk.Tk()
root.geometry("480x480")
root.title("Daily Accounts")
root.resizable(0,0)
app = frame(root)   
root.mainloop()

对于长代码感到抱歉,试图尽可能多地获取信息。

1 个答案:

答案 0 :(得分:1)

这是使用自定义Entry小部件和类方法的理想位置。自定义小部件将从tk.Entry继承,因此它将具有普通Entry小部件的所有属性:

class Ashki(tk.Entry):
    elements = []
    def __init__(self, master=None, **kwargs):
        tk.Entry.__init__(self, master, **kwargs)
        self.elements.append(self)

    @classmethod
    def all_filled(cls):
        return all(entry.get() for entry in cls.elements)

现在,在要包含在支票中的每个位置,请使用Ashki代替tk.Entry

self.entryBags = Ashki(self.frame, validate = 'key', validatecommand = vcmd) 
self.entryBags.place(x = 100, y = 40)  

然后在您的检查方法中,您可以使用以下代码:

if not Ashki.all_filled():
    msgbox.showinfo('Daily Accounts', 'Enter in to entry fields.')
    return # abort this method