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

0 投票
1 回答
1549 浏览
提问于 2025-04-18 04:00

我正在做一个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 个回答

1

你不能把任何东西“返回”给一个按钮,所以在函数最后那些代码是没用的。其实,最简单的办法就是把 inputFileoutputFile 设为全局变量。这样的话,你就不需要把它们作为参数传给 splitSentences() 函数,那个函数可以直接使用它们。

不过,更好的做法是把你的图形界面(GUI)做成一个类,把这些变量变成类的实例变量。你还应该提供一种方法,先把 executeButton 禁用,直到 inputFileoutputFile 有了值,否则那个函数会出错。

撰写回答