简体   繁体   English

“if”语句用于显示错误 tkinter.messagebox 不起作用

[英]"if" statement used to display an error tkinter.messagebox is not working

I'm trying to create a function in where if the values I enter is null a ttk.messagebox will appear to inform the user that the correct values must be entered.我正在尝试创建一个函数,如果我输入的值为空,则 ttk.messagebox 将出现以通知用户必须输入正确的值。 When I enter null values for prce or uprce, it only gives me error messages instead of the messagebox displaying.当我为 prce 或 uprce 输入空值时,它只给我错误消息,而不是显示消息框。 I've tried using a button to make the same messagebox show and it works but now that I try to use an "if" statement for it, it does not show up我已经尝试使用按钮来显示相同​​的消息框并且它可以工作,但是现在我尝试使用“if”语句,它没有显示

Here is my sample code这是我的示例代码

import tkinter
from tkinter import*
from tkinter import ttk, LabelFrame
import tkinter.messagebox
import sqlite3

conn = sqlite3.connect('newtest.db')
c = conn.cursor()

top = tkinter.Tk()

def update(show):
    trv.delete(*trv.get_children())
    for i in show:
        trv.insert("", 'end', values=i)

    return show



def submitprod():
   database_insert()
   current_db_data = query_database()
   update(current_db_data)
   # reset
   pdesc.delete(0, END)
   qty.delete(0, END)
   prce.delete(0, END)
   uprce.delete(0, END)

conn.commit()


def query_database():
    query = "SELECT oid, pdesc, qty, prce, uprce, markup from products"
    conn = sqlite3.connect('newtest.db')
    c = conn.cursor()
    c.execute(query)
    show = c.fetchall()

    return show

def error():

    tkinter.messagebox.showinfo("Error! Enter Value!")

def database_insert():
    conn = sqlite3.connect('newtest.db')
    c = conn.cursor()
    if prce.get == None:
        error()
    if uprce.get == None:
        error()
    pprce1 = int(prce.get())
    uprce1 = int(uprce.get())
    mup = (pprce1 - uprce1 / uprce1 * 100)
    print(mup)
    c.execute("INSERT INTO products VALUES (:pdesc, :qty, :prce, :uprce, :mup1)",{
          'pdesc': pdesc.get(),
          'qty': qty.get(),
          'prce': prce.get(),
          'uprce': uprce.get(),
          'mup1': mup})

    conn.commit()

box2 = LabelFrame(top)
box2.pack (fill="both", expand="yes", padx=20, pady=10)
box1 = LabelFrame(top, text="Entry")
box1.pack (fill="both", expand="yes", padx=20, pady=10)

pdesc = Entry(box1, width=30)
pdesc.grid(row=1, column=1, padx=20)
qty = Entry(box1, width=30)
qty.grid(row=2, column=1, padx=20)
prce = Entry(box1, width=30)
prce.grid(row=3, column=1, padx=20)
uprce = Entry(box1, width=30)
uprce.grid(row=4, column=1, padx=20)

pdesc_label = Label(box1, text='Product')
pdesc_label.grid(row=1, column=2)
qty_label = Label(box1, text='Quantity')
qty_label.grid(row=2, column=2)
prce_label = Label(box1, text='Price')
prce_label.grid(row=3, column=2)
uprce_label = Label(box1, text='Unit Price')
uprce_label.grid(row=4, column=2)

trv = ttk.Treeview(box2, column=(1,2,3,4,5,6), show="headings", height="20")
style=ttk.Style(trv)
style.configure('Treeview', rowheight=20)

trv.pack(side=LEFT)
trv.heading(1, text="Product ID")
trv.heading(2, text="Product Description")
trv.heading(3, text="Quantity")
trv.heading(4, text="Price")
trv.heading(5, text="Unit Price")
trv.heading(6, text="Return Percentage")

#data for products//show1
conn = sqlite3.connect('new1.db')
query = "SELECT oid, pdesc, qty, prce, uprce, markup from products"
c.execute(query)
show = c.fetchall()
update(show)

#submit product button
btn2 = ttk.Button(box1, text='Enter', command=submitprod)
btn2.grid(row=6, column=1, columnspan=1, pady=10, padx=10, ipadx=10)

top.title("error test")
top.geometry("1500x1200")
top.mainloop()

and here is the error message I get这是我收到的错误消息

line 22, in submitprod
    database_insert()
line 54, in database_insert
    pprce1 = int(prce.get())
    ValueError: invalid literal for int() with base 10: ''

You have several errors.你有几个错误。 1) you need to add the () to the end of the get() method 2) you need to compare to an empty string "" , not None 3) you need to add a return to stop the function if an error occurs and 4) you need to provide a title for your error popup. 1) 您需要将 () 添加到get()方法的末尾 2) 您需要与空字符串""进行比较,而不是None 3) 如果发生错误,您需要添加一个return以停止该函数并且4) 您需要为错误弹出窗口提供标题。

if prce.get() == "":
    error()
    return

That said it would be more pythonic to use a try block instead of an if block, like this:也就是说,使用 try 块而不是 if 块会更加 Pythonic,如下所示:

def error():
    tkinter.messagebox.showinfo("Error", "Invalid Value!")

def database_insert():
    try:
        pprce1 = int(prce.get())
        uprce1 = int(uprce.get())
    except ValueError:
        error()
        return # stop this function
    mup = (pprce1 - uprce1 / uprce1 * 100)
    print(mup)

    conn = sqlite3.connect('newtest.db')
    c = conn.cursor()
    c.execute("INSERT INTO products VALUES (:pdesc, :qty, :prce, :uprce, :mup1)",{
          'pdesc': pdesc.get(),
          'qty': qty.get(),
          'prce': prce.get(),
          'uprce': uprce.get(),
          'mup1': mup})

    conn.commit()

That would also catch if the user types "banana" or something.如果用户键入“banana”或其他内容,这也会引起注意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM