2017-11-08 2 views
0

tk filedialog로 열어 선택한 파일의 내용을 읽고 싶습니다. 내가 파일을 선택하고 열기 버튼을 클릭하면 파일이 열리지 않고 대화 상자가 닫힙니다. 파일의 내용을 읽을 수 있도록 메모장에서 선택한 파일을 어떻게 열 수 있습니까? @PM 2RING 및 @Erik에서 힌트tkfiledialog로 파일을 열고 메모장으로 내용을 읽는 방법

from tkinter import * 
from tkinter import filedialog 


def my_file(): 
    filename = filedialog.askopenfile(mode="r", initialdir="/", title="select file", 
             filetypes=(("text files", "*.txt"), ("all files", "*.*"))) 



root = Tk() 
root.geometry("300x300") 
           #open the selected txt file with notepad to read the content 
b = Button(root, text="open text file", command = my_file).pack() 

root.mainloop() 

EDIT 가 나는 파일을 선택할 때 NOTEPAD.EXE 열리고 그것을 반환 할 filedialog.askopenfilename filedialog.askopenfile 변경.

from tkinter import * 
from tkinter import filedialog 
import os 


def my_file(): 
    filename = filedialog.askopenfilename(initialdir="C:/", title="select 
file", filetypes=(("text files", "*.txt"), ("all files", "*.*"))) 
    for f in filename: 
     return f 
    os.system(r"C:/notepad.exe" + f) 


root = Tk() 
root.geometry("300x300") 
          #open the selected txt file with notepad to read 
the content 
b = Button(root, text="open text file", command = my_file).pack() 

root.mainloop() 

그 출력이 오류 : 이 코드입니다

Blockquote'C:/notepad.exet' is not recognized as an internal or external command, operable program or batch file. Blockquote

하지만 난 그것을 terminal.I에 대한 디렉토리를 인쇄 인쇄 반환을 변경할 때 서브 프로세스로 열려고

subprocess.Popen([r'C:\Program Files (x86)\Notepad.exe' + f]) 

이 항목도 열지 않습니다.

+4

메모장에서 파일을 읽으려면 메모장에서 열어 볼까요? 'filedialog.askopenfile'은 텍스트 위젯 내부에 텍스트를 표시하는 것과 같이 Tkinter 프로그램 내에서 사용할 수 있도록 파일을 여는 것입니다. 난 당신이 메모장에서 파일을 열려면 관련된'filedialog.askopenfilename'과'subprocess' 모듈 함수 또는'os.system'을 사용할 수있을 것이라고 생각합니다. 그러나 그것은 좀 이상합니다. IMHO. –

답변

0

여기 몇 가지 수정해야 할 사항이 있습니다.

우선, C:/notepad.exe은 메모장의 위치가 아닙니다 (최소한 기본 설정이있는 Windows 컴퓨터는 아님) notepad.exe을 사용하면 메모장을 다른 위치로 이동 한 시스템과 더 잘 호환 될 수 있습니다 표창장 필요).

둘째, 실행 중입니다. . .

for f in filename: 
    return f 
os.system(r"C:/notepad.exe" + f) 

당신이 생각하는 것처럼 보이지 않습니다. 여기서 실제로 일어나고있는 것은 프로그램이 문자열을 루프에로드하고 첫 번째 문자 (아마 "C")를 평가 한 다음 반환 된 값을받지 않는 Button 위젯에 문자열을 반환한다는 것입니다. 이렇게하면 함수가 깨져서 실제로는 os.system(r"C:/notepad.exe" + f)이라는 선언에 도달하지 않습니다.

은 또한 그렇지 않으면 당신은 당신 오류가 발생하는 것입니다 notepad.exeC:/text.txt 같은 것을 실행하고, 메모장 notepad.exe 실제 파일 선언 f을 여는 데 사용되는 문 사이에 공백을 포함해야합니다.나는 당신이이 일을하는 이유 단서가 없다는 것을 추가 할

from tkinter import * 
from tkinter import filedialog 
import os 

def my_file(): 
    filename = filedialog.askopenfilename(initialdir="C:/", title="select file", filetypes=(("text files", "*.txt"), ("all files", "*.*"))) 
    os.system(r"notepad.exe " + filename) 

root = Tk() 
root.geometry("300x300") 
b = Button(root, text="open text file", command = my_file).pack() 

root.mainloop() 

, 왜 단순히 Text 위젯에 텍스트를 표시하지 : 당신이 일을해야 무엇

는 다음과 같은 것입니다 ? 여기서하고있는 일은 파일 탐색기를 열지 않고 파일을 찾은 다음 프로그램을 열고 파일 탐색기를 연 다음 파일을 찾은 다음 메모장에서 파일을 열 수있는 추가 단계를 추가하는 것입니다. 열어 봐. 그것은 당신의 프로그램의 로딩 시간은 말할 것도없고 적어도 하나의 여분의 클릭을 추가하고 있습니다.

+0

이 있어야합니다. notepad.exe에 대한 excel 및 csv 때문에 Excel.exe를 실행하려고했기 때문에 xls 확장을 변경하면 열리지 않습니다. –

+0

다른 질문입니다. 새로운 질문을 제기하십시오. –

+0

학습 목적으로 만 다른 응용 프로그램으로 열려고합니다. –

0

다음 코드는 버튼과 텍스트 위젯을 표시합니다. 버튼이 파일에로드되고 텍스트 위젯이이를 표시합니다. 나는 이것이 당신이 염두에 두었던 것이라고 생각 하나? 오후 2Ring에서 언급 한 바와 같이

from tkinter import * 
from tkinter import filedialog 

def my_file(): 
    file = filedialog.askopenfile(mode="r", initialdir="/", title="select file", 
            filetypes=(("text files", "*.txt"), ("all files", "*.*"))) 
    t.insert(END, file.read()) 
    file.close() 

root = Tk() 
root.geometry("300x300") 
          #open the selected txt file with notepad to read the content 
t = Text(root) 
t.grid(row=0, column=0) 
b = Button(root, text="open text file", command = my_file) 
b.grid(row=1, column=0) 

root.mainloop() 
+0

AttributeError : 'NoneType'객체에 'grid'속성이 없습니다. 위젯에 대해 pack과 grid를 동시에 사용 중입니다. 제발 당신의 대답에 덧글을 추가 할 수 있습니다 –

+0

미안, 나는 거기에 그 추가'팩'을 남기려고하지 않았다. –

+0

당신은 내 잘못이야. 필자는 몇 년 동안 글로벌 변수를 사용하는 코드를 작성하지 않았으므로 약간 퍼지기에 안전하다고 판단했습니다. –

1

, 나는 os.system 기능을 사용할 수 있습니다. 설명에서 언급했듯이 "os.system (command)"은 명령 프롬프트에서 작성한 것처럼 명령을 실행합니다. 따라서 os.system("Notepad c:/users/yourName/junk.txt)은 junk.txt 파일이 해당 위치에 있었던 경우 엽니 다. 당신이 당신의 filedialog.askopenfilename 전화에서 파일 이름을 일단 즉

은이 같은 수행

import os 
os.system("Notepad " + filename) # where filename is the string that filedialog.askopenfilename returns 

이 코드로 구현이 너무 나쁘지 않을해야합니다,하지만 당신은 더 완전한 예제를 필요로하는 경우 알려주세요.

+0

os.system ("notepad.exe"+ f)를 호출하면 notepad.exe 다음에 공백이 누락됩니다. os.system ("notepad.exe"+ f) – Erik

관련 문제