如何将Entry Widget传递给函数?

时间:2015-04-01 16:01:06

标签: python-3.x tkinter

我确定这是一个简单的错误,我已将其本地化为代码中的特定位置:

class NewProduct(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)                

        tLabel = ttk.Label(self, text="Title: ", font=NORM_FONT).grid(row=0, padx=5, pady=5)
        qLabel = ttk.Label(self, text="Quantity: ", font=NORM_FONT).grid(row=1, padx=5, pady=5)
        pLabel = ttk.Label(self, text="Price: $", font=NORM_FONT).grid(row=2, padx=5, pady=5)
        te = ttk.Entry(self).grid(row=0, column=1, padx=5, pady=5) # Add validation in the future
        qe = ttk.Entry(self).grid(row=1, column=1, padx=5, pady=5)
        pe = ttk.Entry(self).grid(row=2, column=1, padx=5, pady=5)

        saveButton = ttk.Button(self, text="Save", command=lambda: self.save(self.te.get(), self.qe.get(), self.pe.get()))
        #WHY IS THIS WRONG!!!!!???!?!?!?!?!?
        saveButton.grid(row=4, padx=5)
        cancelButton = ttk.Button(self, text="Cancel", command=lambda: popupmsg("Not functioning yet."))
        cancelButton.grid(row=4, column=1, padx=5)

    def save(self, title, quantity, price):
        conn = sqlite3.connect("ComicEnv.db")
        c = conn.cursor()
        c.execute("INSERT INTO cdata(unix, datestamp, title, quantity, price) VALUES (?,?,?,?,?)",
                  (time.time(), date, title, quantity, price))
        conn.commit()
        conn.close()

我尝试了一些不同的东西,包括: saveButton = ttk.Button(self, text="Save", command=lambda: self.save(te.get(), qe.get(), pe.get()))

我正在尝试从条目窗口小部件获取用户输入并将其存储在sqlite3数据库中。

这是追溯:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:\Users\aedwards\Desktop\deleteme.py", line 106, in <lambda>
    saveButton = ttk.Button(self, text="Save", command=lambda: self.save(self.te.get(), self.qe.get(), self.pe.get()))
AttributeError: 'NewProduct' object has no attribute 'te'

你们可以给我的任何帮助将不胜感激。更多信息,请告诉我。

提前致谢!

1 个答案:

答案 0 :(得分:6)

错误告诉您问题:NewProduct对象没有名为te的属性。您已创建名为te的局部变量,但要将其作为属性,您必须创建self.te

此外,您必须在创建窗口小部件的单独语句中调用grid,因为grid(...)会返回None,因此teself.te会也没有。这不仅可以解决这个问题,还可以让您的代码更容易理解,因为您可以将所有调用grid放在同一代码块中,这样您就不会将布局分散到各处。

例如:

def __init__(...):
    ...
    self.te = ttk.Entry(...)
    self.qe = ttk.Entry(...)
    self.pe = ttk.Entry(...)
    ...
    self.te = grid(...)
    self.qe = grid(...)
    self.pe = grid(...)

FWIW,我建议在这里使用lambda not 。为您的按钮创建一个正确的功能来调用。编写和调试比复杂的lambda容易得多。很少需要在tkinter中使用lambda

例如:

def __init__(...):
    ...
    saveButton = ttk.Button(..., command=self.on_save)
    ...

def on_save(self):
    title=self.te.get()
    quantity = self.qe.get()
    price = self.pe.get()
    self.save(title, quantity, price):
相关问题