我很难弄清楚如何将变量从一类传递到另一类。在我的代码中,我有一个函数,该函数保存数据库项的主键。我想将该变量传递到一个单独的类中使用,但我不知道如何。变量的名称为classID,我想将其传递给类'class_menu'。任何帮助都非常感谢。
这是我的代码:
class class_search_2(tk.Frame):
def __init__(self,parent,controller):
self.controller = controller
tk.Frame.__init__(self,parent)
lbl = ttk.Label(self,text="Class Search",font=("Arial",20)).pack()
lbl2 = ttk.Label(self,text="Class Name").place(rely=0.3,relx =0.25,x=0,y=0)
lbl3 = ttk.Label(self,text="Class Year").place(rely=0.4,relx =0.25,x=0,y=0)
self.box1 = ttk.Entry(self,width="25")
self.box2 = ttk.Entry(self,width="25")
btn1 = ttk.Button(self, text="Search",width="15",
command= self.search_2)
btn2 = ttk.Button(self,text="Back To Menu",width="15",
command=lambda: controller.show_frame(menu_2))
btn1.place(rely=0.8,relx =0.5,x=0,y=0,anchor="center")
btn2.place(rely=0.94,relx =0.85,x=0,y=0,anchor="center")
self.box1.place(rely=0.3,relx =0.52,x=0,y=0)
self.box2.place(rely=0.4,relx =0.52,x=0,y=0)
def search_2(self):
classname = self.box1.get()
classyear = self.box2.get()
find_class = ('''SELECT * FROM classes WHERE classname = ? AND classyear = ?''')
cursor.execute(find_class,[(classname),(classyear)])
results = cursor.fetchall()
for row in results:##Fetches the first row of the column being classID and saves in a variable
self.classID = (row[0])
if results:
self.controller.show_frame(class_menu)
self.box1.delete(0, 'end')
self.box2.delete(0, 'end')
else:
messagebox.showerror("Error","No class found in Database")
##Function works same as login. Fetches two variables and matcbes against db. If match is found
##then loads up the classes students. If not an error message appears.
class class_menu(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
lbl = ttk.Label(self,text="Class Menu (Admin)",font=("Arial",20)).pack()
btn1 = ttk.Button(self, text="Remove Class",width="15",)
btn2 = ttk.Button(self, text="Display Students",width="15")
btn3 = ttk.Button(self, text="Add Students",width="15")
btn4 = ttk.Button(self,text="Back To Menu",width="15",
command=lambda: controller.show_frame(menu_2))
btn1.place(rely=0.435,relx =0.5,x=0,y=0,anchor="center")
btn2.place(rely=0.550,relx =0.5,x=0,y=0,anchor="center")
btn3.place(rely=0.675,relx =0.5,x=0,y=0,anchor="center")
btn4.place(rely=0.94,relx =0.85,x=0,y=0,anchor="center")
答案 0 :(得分:0)
class class_search_2():
def __init__(self):
self.classID = None
def search_2(self):
self.classID = 5 # I assumed that
class class_menu():
def __init__(self, classID):
self.classID = classID
def print_classID_in_class_menu(self):
print(self.classID)
obj1 = class_search_2()
obj1.search_2()
print("ClassID is ", obj1.classID)
obj2 = class_menu(obj1.classID)
obj2.print_classID_in_class_menu()
我简化了问题。您可以创建一个对象,然后使用该对象attirubute将classID
的值传递给另一个类。