본문 바로가기
파이썬

파이썬 Tkinter에서 파일 저장 대화 상자

by º기록 2021. 1. 4.
반응형

파이썬에서 GUI 기반 텍스트 편집기를 구현하고 있습니다.
텍스트 영역을 표시했지만 Tkinter에서 asksaveasfile 메서드를 사용하려고하면 파일이 저장되었음을 표시하지만 데스크톱 편집기에서 동일한 파일을 열려고하면 빈 파일이 표시됩니다.

만 파일이 생성되고 저장됩니다. 그 내용은 아닙니다.

이유를 알고 싶습니다. 내가 뭘 잘못하고 있니? 내 코드는 다음과 같습니다.

from Tkinter import *
import tkMessageBox
import Tkinter
import tkFileDialog

def donothing():
   print "a"

def file_save():
    name=asksaveasfile(mode='w',defaultextension=".txt")
    text2save=str(text.get(0.0,END))
    name.write(text2save)
    name.close

root = Tk()
root.geometry("500x500")
menubar=Menu(root)
text=Text(root)
text.pack()
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=file_save)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

editmenu=Menu(menubar,tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)

helpmenu=Menu(menubar,tearoff=0)
helpmenu.add_command(label="Help",command=donothing)
menubar.add_cascade(label="Help",menu=helpmenu)

root.config(menu=menubar)
root.mainloop()  

 

해결 방법

 

함수 이름은 asksaveasfilename 입니다. 그리고 tkFileDialog.asksaveasfilename 으로 규정되어야합니다. 그리고 mode 인수를 허용하지 않습니다.

tkFileDialog.asksaveasfile 을 사용하고 싶을 수도 있습니다.

def file_save():
    f = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
    if f is None: # asksaveasfile return `None` if dialog closed with "cancel".
        return
    text2save = str(text.get(1.0, END)) # starts from `1.0`, not `0.0`
    f.write(text2save)
    f.close() # `()` was missing.

 

참조 페이지 https://stackoverflow.com/questions/19476232

 

 

반응형

댓글