2014-04-23 86 views
0

我正在開發一個tkinter接口,用於打開文件,讀取和修改文件,然後將其輸出到新文件。我點擊按鈕後,讓用戶瀏覽他們的計算機以獲取適當的文件。這些單獨的函數返回文件名(「randomInputFile.txt」)。Python的tkinter按鈕 - 如何從其他按鈕獲取函數的返回值?

我的問題是,我有第三個按鈕,應該採取這兩個值,然後在讀/寫過程中使用它們。我不知道如何將輸入/輸出文件名作爲參數傳遞給讀/寫功能。

我應該在相應的函數中將文件名作爲全局變量傳遞嗎?

from tkinter.filedialog import askopenfilename 
from tkinter.filedialog import asksaveasfilename 
def openGUI(): 
    wn = Tk() 
    wn.title("Homework 10 - CSIS 153") 

    openFileButton = Button(wn, text="Open", command = openFile) 
    openFileButton.pack() 
    openFileButton.place(bordermode=OUTSIDE, height=90, width=90) 

    saveFileButton = Button(wn, text="Save to...", command = saveFile) 
    saveFileButton.pack() 
    saveFileButton.place(bordermode=OUTSIDE, height=90, width=90, x=110,) 

    executeButton = Button(wn, text="Run Program", command = splitSentences(****SOMETHING, SOMETHING****)) 
    executeButton.pack() 
    executeButton.place(bordermode=OUTSIDE, height=90, width=123, x=40, y=115) 

    wn.mainloop() 

def openFile(): 
    inputFile = askopenfilename() 
    msg = "You are opening:\n\n" + str(inputFile) 
    messagebox.showinfo("File Location", msg) 
    return inputFile 

def saveFile(): 
    outputFile = asksaveasfilename() 
    return outputFile 
def splitSentences(inFile, outFile): 
    with open(inFile) as myFile: 
     #etc etc 

回答

1

你不能return任何一個按鈕,所以有在函數結束時這些線路沒有用。是的,最簡單的做法是製作inputFileoutputFile全局變量。然後,您也不需要將它們作爲參數傳遞給splitSentences(),該函數將直接訪問它們。

但是,更好的方法是讓你的GUI成爲一個類,然後把這些變量作爲實例變量。除非inputFileoutputFile變量的值存在,否則您還應提供某種方法來禁用executeButton,否則該函數將引發錯誤。

+0

謝謝你的建議。因爲這是一個學校作業,我只會在一些先決條件下寫或提出一些相關的錯誤消息。 – ThePeter