[英]Passing Tkinter variable from one function to another
我很難弄清楚如何將變量從一個 class 傳遞到另一個。 在我的代碼中,我有一個 function ,它包含數據庫項的主鍵。 我想將該變量傳遞給單獨的 class 以供使用,但我不知道如何使用。 該變量是名稱 classID,我想將其傳遞給 class '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")
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()
我簡化了問題。 您可以創建一個 object 並使用此 object 屬性將classID
值傳遞給另一個 class。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.