[Tutor] How to write lines in a text file (GUI)

Mic o0MB0o at hotmail.se
Tue Nov 29 19:02:52 CET 2011


Hey again.

I figured I would first post this piece of code and then ask my questions.

FREE = "green"
OCCUPIED = "red"

class Mainwindow(Frame):
     def __init__(self,master):
         super(Mainwindow,self).__init__(master)
         self.grid()
         self.create_mainwidgets()

     def create_mainwidgets(self):
         self.klicka=Button(self, text="Press the button",
                            command=self.uppdatera)
         self.klicka.grid()

     def uppdatera(self):
         SeatWindow(root)

class SeatButton(tk.Button):
     def __init__(self, master, index):
         text = str(index+1)
         super(SeatButton, self).__init__(master,
                                          text=text, bg=FREE,
                                          command=self.clicked)
         self.filename = "Germany_France{}.txt".format(index+1)
         self.occupied = False
         if os.path.exists(self.filename):
              self["bg"]=OCCUPIED

     def clicked(self):
         self.occupied = not self.occupied
         if self.occupied:
             self["bg"] = OCCUPIED
             text_file=open(self.filename,"w")
             text_file.write(self.filename)
             text_file.close()
         else:
             self["bg"] = FREE
             os.remove(self.filename)

class SeatWindow(tk.Toplevel):
      def __init__(self, master):
          super (SeatWindow, self).__init__(master)
          self.grid()
          self.create_widgets()

      def create_widgets(self):
          for index in range(20):
              button = SeatButton(self, index)
              row, column = divmod(index, 4)
              button.grid(row=row, column=column)

root=Tk()
root.title("testV2")
app=Mainwindow(root)
root.mainloop()




I am now writing another program. It turned out just fine, but I have one
question.

If button one is pressed I want the program to write, say hi_1, on the first
line in a text file.
If button one is pressed again, the first line should be empty.

If button two is pressed I want the program to write hi_2 in the second line
in the text file.
If button two is pressed again, the second line in the text file should be
empty.

If button three is pressed I want the program to write hi_3 in the third
line in the text file.
if button three is pressed again, the third line in the text file should be
empty.

There shouldn't be any other changes to the program other than this above.
There is already a text file
created, the program doesn't need to create one. We can call that file "Hi".


I hope you understand what I want to do here. I have tried the entire
evening yesterday to get this to work, I tried using writeline() but I can't
get it to work.
What are your suggestions to this?



Thank you for your help and time!



More information about the Tutor mailing list