2014-01-06 40 views
-1

在我的程序中,用戶被要求提供他們的名字,姓氏和高中班級。在程序的最後有一條if語句,如果符合條件,那麼我想創建一個文件,它將打印這些變量以及一條或兩條消息。如何從python中的用戶輸入創建文本文件?

我也想要求用戶輸入一個關於他們自己的簡短聲明,所以基本上是一個文本項目,這也是要添加到文件中。

class Score_Window(tk.Toplevel): 
'''A simple instruction window''' 
def __init__(self, parent): 
    tk.Toplevel.__init__(self, parent) 
    score_str = str(sum(parent.score_per_question.values())) 
    self.score = tk.Label(self, width=80, height=4, text = "You're score was: " + score_str) 
    self.score.pack(side="top", fill="both", expand=True) 


    if int(score_str) >= 3: 
     print("Pass") 

     self.prefect = tk.Label(self, width=80, height=4, text = "You have passed, well done! You can now become a prefect.") 
     self.prefect.pack(side="top", fill="both", expand=True) 

     self.name = tk.Label(self, width=80, height=4, text = student_name) 
     self.name.pack(side="top", fill="both", expand=True) 

     self.surname = tk.Label(self, width=80, height=4, text = student_surname) 
     self.surname.pack(side="top", fill="both", expand=True) 

     self.tutor = tk.Label(self, width=80, height=4, text = student_tutor_group) 
     self.tutor.pack(side="top", fill="both", expand=True) 

我要打印這些變量到文件

else: 
     print("Fail") 

     self.fail = tk.Label(self, width=80, height=4, text = "Unfortunately you have not scored highly enough to be considered for a prefect position.") 
     self.fail.pack(side="top", fill="both", expand=True) 
+4

你有沒有爲此編寫過任何代碼?你真正的問題是什麼?沒有人想要爲你寫代碼,如果你甚至沒有自己去。不要試圖變得討厭或者任何事情,但是你會首先嚐試自己,並在你真正陷入困境時來到這裏尋求指導。我保證你會有實際的問題然後:) – Totem

+0

如果你表明你已經付出了一些努力來解決這個問題,你會更成功地找到答案。 – That1Guy

+0

如果你有一個特定的問題,請自己先編寫它自己的代碼http://docs.python.org/2/tutorial/inputoutput.html回來。我們不會從頭開始編寫代碼。 – CoryKramer

回答

0

您可以使用Python的公開聲明和使用tksimpiledialog讓輸入做到這一點。 假設你已經設置類:

from Tkinter import * # tkinter in 3.0+ 
from tkSimpleDialog import askstring 

Name = tkSimpleDialog.askstring("User data","Please enter your name") 
Surname = tkSimpleDialog.askstring("User data", "Please enter your surname") 
somevariable = open("data.txt", "w") 
somevariable.write(Name, " ",Surname) # add a space so it is easier to read 
userinfo = tkSimpleDialog.askstring("User data", "Enter something about yourself") 
somevariable.write(" ",userinfo 
# make if statements and a new canvas 
with open("data.txt", "r") as l 
    for lines in l: 
     name2, Surname2, userinfo2 = lines.split() 
     namelabel = label(master, text=name2) 
     namelabel.pack() 
     surnamelable = label(master, text=Surname2) 
     surnamelable.pack() 
     Userinfolabel = label(master, text= userinfo2) 
     Userinfolabel.pack() 
     # do whatever you want here, perhaps a reset button? 

你必須設置主tk類和初始化手動因爲我不知道還有什麼您的代碼。而且我甚至不知道if語句的測試條件!

+0

文件模式不應該是apend - 「a」或寫 - 「w」 –

+0

@ChetanVasudevan不知道OP究竟打算做什麼,我在編輯之前根據原始問題對它進行編碼,只需要讀訪問。 – Dashadower

+0

是的,我意識到:)。 –

相關問題