0

my code is to display the gui then enter the text in it, after clicking the save text button, it should appear in file.txt.

I tried the save function

def save():
  with open('test.txt', 'w') as f:
       my_text = txt.toPlainText()
       f.write(my_text)

This function is to read this code

  txt = tk.Text(self, bd=3, exportselection=0, bg='WHITE', font='Helvetica',
          padx=10, pady=10, height=5, width=30)

  txt.pack()

The problem is that the text.txt file does not overwrite itself

The entire code looks like this

class PageNumber(tk.Frame):

  
   def __init__(self, parent, controller):

       def save():
       with open('test.txt', 'w') as f:
           my_text = txt.toPlainText()
           f.write(my_text)

       tk.Frame.__init__(self, parent)
       self.controller = controller
       self.configure()

       txt = tk.Text(self, bd=3, exportselection=0, bg='WHITE', font='Helvetica',
                padx=10, pady=10, height=5, width=30)
       txt.pack()

       btnsave = tk.Button(self, text="Zapisz wynik", padx=35, pady=10, fg="#ffffff", bg="#263942", 
       command=save)
       btnsave.pack(fill="x")
  • Not seeing any `toPlainText` method for a Text widget in tkinter doc. Also you seem to use `txt` in your definition of the `save` function before assigning `txt` to be then Text widget. So is whatever `txt` in the `save` function something else that has a `toPlainText` method that you defined in global scope? – Andrew Allaire Feb 08 '21 at 21:55
  • do you have idea? @AndrewAllaire – Szymon Szteniowicz Feb 11 '21 at 11:46
  • Yes, make your text widget an attribute of your PageNumber object. For example `self.txt` rather than `txt`. When I do tkinter I find works well to make all my widgets attributes of objects, and all the callbacks methods of those objects. This means any of the methods have access to any of the widgets. – Andrew Allaire Feb 11 '21 at 15:14
  • changed to self.txt2 and self.txt2.toPlainText () but now an error pops up File "C: /Users/Szymo/Pulpit/Inzynierka/Interface.py", line 199, in save f.write (my_text) TypeError: write () argument must be str, not None @AndrewAllaire – Szymon Szteniowicz Feb 15 '21 at 12:57
  • Not sure I can debug it without seeing the new way you got the code. But the error message is telling you that `my_text` is not the text at all, but simply a `None`. To get the text from the Text widget you should be doing it like this: https://stackoverflow.com/questions/14824163/how-to-get-the-input-from-the-tkinter-text-widget – Andrew Allaire Feb 15 '21 at 15:20

0 Answers0