Got the AttributeError: 'FarmerClass' object has no attribute 'farmer_name' in the following code

Got the AttributeError: 'FarmerClass' object has no attribute 'farmer_name' in the following code

我正在尝试解决自动完成下拉组合框的问题,它适用于数据库。但是当我在运行时更新数据库后尝试获取数据时,我得到了 AttributeError: 'FarmerClass' object has no attribute 'farmer_name'。我尝试了其他可用的解决方案,但仍然没有解决错误。截至目前,从我所遵循的参考代码来看,拼写错误和语法看起来不错。

抛出错误的class

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

        self.veg = []
        self.farmer = []
        self.buyers = []

        self.fetch_data()
        
        self.farmer_name = ttk.Combobox(self)
        self.farmer_name['values'] = self.farmer
        self.farmer_name.focus()
        self.farmer_name.bind('<KeyRelease>', self.check_name)
        self.farmer_name.bind('<<ComboboxSelected>>', self.get_data)
        self.farmer_name.place(relx=0.028, rely=0.243, width=240, height=24)

        self.product = ttk.Combobox(self )
        self.product['values'] = self.veg
        self.product.bind('<KeyRelease>', self.check_veg)
        self.product.place(relx=0.028, rely=0.380,width=240, height=24)

        self.buyer = ttk.Combobox(self )
        self.buyer['values'] = self.buyers
        self.buyer.bind('<KeyRelease>', self.check_buyer)
        self.buyer.place(relx=0.028, rely=0.5237,width=240, height=24)

        #======================= Entry btn ====================
        self.entry_btn = tk.Button(self,Btn_base, text='Entry', command=self.entry_to_bill)
        self.entry_btn.place(relx=0.481, rely=0.525,width=134, height=24)
    
    def fetch_data(self, event=None):
        cur.execute('SELECT * FROM vegetable ')
        for i in cur.fetchall():
            self.veg.append(i[0])
        
        cur.execute('SELECT rowid, * FROM farmers ')
        for i in cur.fetchall():
            self.farmer.append(i[2])
        
        cur.execute('SELECT rowid,name FROM buyers_avail ')
        for i in cur.fetchall():
            self.buyers.append(i[1])

        self.farmer_name.configure(values= self.farmer) # getting error here
        self.product.configure(values= self.veg)
        self.buyer.configure(values= self.buyers)
            
    def entry_to_bill(self, event=None):
        name = self.buyer.get().lower()
        cur.execute('SELECT name FROM buyers_avail WHERE name = ? ', [name])
        bnames = cur.fetchall()
        if bnames:
            print(f'buyer {bnames} found')
        else:
            cur.execute('INSERT INTO buyers_avail (name) VALUES (?)',[name,])
            db.commit()
        self.buyer.delete(0, tk.END)
        self.buyer.focus()
        self.fetch_data()

如果我尝试不使用这些行,farmer_name 看起来不错,product 得到 buyers 的值并且 buyer 下拉列表变为空。 请询问是否需要与问题相关的内容。

fetch_data 函数访问 farmer_name 但您在定义 farmer_name 之前调用它,因此此时不存在。您需要在 定义 farmer_name.

后调用 fetch_data