Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...