2017-06-05 81 views
0
的另一個定義以TXT數據

我的代碼是這樣看現在:的Tkinter從按鈕

def browse_button(): 
    ftypes1 = [('file', '*.txt')] 
    filename1 = filedialog.askopenfilename(filetypes = ftypes1) 
    print(filename1) 
    with open(filename1) as newfile1: 
     file1 = pd.read_table(newfile1, sep=',', names=('A', 'B', 'C')) 
     print file1 

    return filename1 

def file_button(): 
    abc=browse_button() 
    print abc 
        # in this definition i want to work on the input file that 
        i have imported at start in browse_button definition,but 
        it doesn't work good 

我使用這個代碼來運行他們他們

if __name__ == '__main__': 
    root = Tk() 
    root.title('title') 
    root.geometry("450x150+200+200") 
    b1 = Button(root, text='one', font=('arial', 12), command=browse_button) 
    b1.pack(side=LEFT, padx=5, pady=5) 
    b6 = Button(root, text='file', font=('arial', 12), command=file_button) 
    b6.pack(side=LEFT, padx=5, pady=5) 

感謝您的諮詢!

+0

第一塊被打破 –

+0

@Bryan奧克利,修正的壓痕,我只是把它複製在錯誤的方式,但它仍然犯規解決它似乎是問題 – Pawe

回答

0

在你的問題中,你已經聲明你想處理你打開的文件,但你所做的只是返回文件名。

return(filename1)您的browse_button()函數中的這條語句只返回文件名到file_button()而不是數據。在結果說,文件名是my_fileprint abc將導致:my_file

如果您創建變量filename1所有你正在做的是獲取文件名。如果您嘗試使用該文件的內容,則需要從with open語句中返回file1

更新:

我創建了打開我創建一個文本文件,將使用第二個函數打印出的內容類似的代碼。

編輯:我將你的按鈕添加到我的答案,所以你可以看到它應該如何一起看。

# Python 3 imports 
from tkinter import * 
from tkinter.filedialog import askopenfilename 

# Python 2 imports 
# from Tkinter import * 
# from tkFileDialog import askopenfilename 

def browse_button(): 
    ftypes1 = [('file', '*.txt')] 
    filename1 = askopenfilename(filetypes = ftypes1) 
    with open(filename1) as newfile1: 
     file1 = newfile1.read() 
     print (file1) 

    return filename1 

def file_button(): 
    abc=browse_button() 
    print (abc) 

if __name__ == '__main__': 
    root = Tk() 
    root.title('title') 
    root.geometry("450x150+200+200") 
    b1 = Button(root, text='one', font=('arial', 12), command=browse_button) 
    b1.pack(side=LEFT, padx=5, pady=5) 
    b6 = Button(root, text='file', font=('arial', 12), command=file_button) 
    b6.pack(side=LEFT, padx=5, pady=5) 

    root.mainloop() 

結果:

Content of my_file! 
+0

和我已經寫過的一樣,然後當我運行腳本窗口自動打開時,我將'abc = openFile()'添加到'def WortkWithFile()',我不知道爲什麼,它應該等到我按下按鈕;/ – Pawe

+0

@Pawe:如果你複製了我的代碼,那麼在程序啓動時會調用函數'workWithFile()'。你可以刪除它。我只用它作爲例子。它和 –

+0

不一樣。我正在返回文件的內容。在你寫的代碼中,你試圖返回文件名。 –