我有下面的代碼,我試圖讓用戶打開一個文本文件,並且一旦用戶選擇了它,我希望代碼讀取它(這不是一個完整的代碼塊,只是爲了展示我的後面)。用askopenfilename打開和讀取文件
但是,我使用tkFileDialog.askopenfilename並添加'mode ='rb''或使用下面的代碼和使用讀取它會產生一個錯誤的困難。
有誰知道我可以如何安排這樣做,因爲我不希望爲每個項目(如Menu和Listbox)輸入Tkinter.'module'。初學者到Tkinter,有點困惑!謝謝您的幫助!
import sys
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfilename # Open dialog box
fen1 = Tk() # Create window
fen1.title("Optimisation") #
menu1 = Menu(fen1)
def open():
filename = askopenfilename(filetypes=[("Text files","*.txt")])
txt = filename.read()
print txt
filename.close()
fen1.mainloop()
很顯然,我到達這裏的錯誤是:
AttributeError: 'unicode' object has no attribute 'read'
我不明白如何使用askopen,也能讀我打開該文件。
你不妨先從一個簡單的問題:你可以寫,打開並打印特定文件Python程序,說'在/ etc/passwd'或其他一些簡單的,已知對存在,文件? – sarnold
我以前曾使用過讀寫文本文件,但從未使用過Tkinter,打開文件後它有點困惑。我需要剝去文件名嗎? – user2063