我更新了這個問題。我創建了兩個窗口,並嘗試將A類中創建的變量傳遞給B類。請指出我的代碼中存在哪些問題?這裏是我的方法:如何將變量從一個類傳遞給另一個類?
class Welcome:
def __init__(self, master, csv_name_sub, csv_name_ses):
self.entrySes = Entry(self.master, bg="LemonChiffon3")
self.entrySub=Entry(self.master,bg="LemonChiffon3")
self.csv_name_sub = str(self.entrySub.get())
self.csv_name_ses = str(self.entrySes.get())
#here users enter some info, they are saved to be used as file name the in following class
class App(Welcome):
def __init__(self, master):
Welcome.__init__(self, master, csv_name_ses, csv_name_sub) #I'm trying use this line to pass the variables from the first class
print('session is', self.csv_name_ses)
print("subject is", self.csv_name_sub)
self.resultFile = open(
"C:\\Users\\xxx" + self.csv_name_sub + '_' + self.csv_name_ses +
'_results.csv', 'w')
#.....
#other codes
def main():
root = Tk()
myApp = Welcome(root, csv_name_ses, csv_name_sub)
root.mainloop()
if __name__ == '__main__':
main()
程序可以運行,但變數csv_name_ses
和csv_name_sub
不傳遞給class App
,因爲它們不是在課堂上打印出來。
我也嘗試過的Composition如下的方法,仍然不能解決問題:
class Welcome:
def __init__(self, master, csv_name_sub, csv_name_ses):
self.entrySes = Entry(self.master, bg="LemonChiffon3")
self.entrySub=Entry(self.master,bg="LemonChiffon3")
self.csv_name_sub = str(self.entrySub.get())
self.csv_name_ses = str(self.entrySes.get())
class App:
def __init__(self, master, csv_name_ses, csv_name_sub):
self.csv_name_sub = csv_name_sub
self.csv_name_ses = csv_name_ses
self.welcomePage = Welcome(master, csv_name_ses, csv_name_sub)
print('session is', self.welcomePage.csv_name_ses)
print("subject is", self.welcomePage.csv_name_sub)
self.resultFile = open(
"C:\\Users\\xxx + self.welcomePage.csv_name_sub + '_' + self.welcomePage.csv_name_ses +
'_resultsofPart.csv', 'w')
謝謝!
接受它們作爲參數(有幾種方法)並調用基類。您還需要創建一個實例'App'*,它是*'Welcome'的子類 - 在子類場景中只創建一個* instance *,並且想到「傳遞給類」會產生混淆。或者,歡迎您成爲App的子類更合適?或者,使用Composition可能會更簡單,更容易混淆? – user2864740
感謝您的評論和建議。我試圖使用組合,但仍不能使用子類中的變量。我已經更新了這個問題,請介意幫我看一下嗎?謝謝 – Kay