Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

tkinter - Write text and save dialog

from tkinter import * 
from tkinter import ttk 
from tkinter.filedialog import asksaveasfile 
  
root = Tk() 
root.geometry('200x150') 

Text = ['word','great','text']

def save(): 
    text_file = asksaveasfile(title="Select Location", filetypes=(("Text Files", "*.txt"),))

    with open(text_file, 'w') as f:
        f.write(Text)


btn = ttk.Button(root, text = 'Save', command = lambda : save()) 
btn.pack(side = TOP, pady = 20)
  
mainloop()

TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper

I have a list called Text. I want to print the contents of the list into a text file. What should I do?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is something that works for me:

lst = ['Hello There
', 'How are ya
', 'All good?
']

def save(): 
    text_file = asksaveasfile(title="Select Location", filetypes=(("Text Files", "*.txt"),))
     for line in lst:
         text_file.write(line) # Use str(line) if lst is of integers

The mistake is that asksaveasfile returns a _io.TextIOWrapper object, meaning its same as using open(...) one a file. What you wanted was asksaveasfilename() which will return the path of the object, then:

def save(): 
    text_file = asksaveasfilename(title="Select Location", filetypes=(("Text Files", "*.txt"),))
    with open(text_file, 'w') as f:     
        for line in lst:
            f.write(line) # Use str(line) if list of integers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...