Python的tkinter按钮 - 如何从其他按钮获取函数的返回值?

时间:2014-04-23 22:14:52

标签: python user-interface python-3.x tkinter

我正在开发一个tkinter接口,用于打开文件,读取和修改文件,然后将其输出到新文件的作业。我有按钮,当点击时,让用户浏览他们的计算机以获取相应的文件。这些单独的函数返回文件名(“randomInputFile.txt”)。

我的问题是我有第三个按钮,应该取这两个值,然后在读/写过程中使用它们。我不确定如何将输入/输出文件名作为参数传递给读/写函数。

我是否应该将文件名作为全局变量传递给相应的函数?

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 个答案:

答案 0 :(得分:1)

你不能return任何按钮,所以在函数末尾的那些行中没有用处。是的,最简单的方法是制作inputFileoutputFile个全局变量。然后,您也不需要将它们作为参数传递给splitSentences(),该函数只是直接访问它们。

然而,更好的方法是将GUI作为一个类,将这些变量作为实例变量。您还应该提供一些方法来禁用executeButton,直到您拥有inputFileoutputFile变量的值,否则该函数将引发错误。

相关问题