从闭包返回值并在其他模块中使用它

时间:2018-05-30 09:23:19

标签: python python-3.x tkinter

我试图从其他模块中的闭包中获取值。当我按下GUI中的按钮时,文件对话框会创建一个包含文件路径的字符串(因此此步骤有效)。然后可以在main.py中访问该字符串。此步骤不起作用,main始终None

这就是我在文件main.py中的内容:

import mat_import
import GUI

filename1 = GUI.gui()

print(filename1)

这就是我在GUI.py中所拥有的

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
import os
import math
import sys

def gui():
    mainpage = Tk()   

    def choose_file1():
        filename1 = filedialog.askopenfilename()
        lbl_read_file1_path = Label()
        lbl_read_file1_path.configure(text = filename1)
        lbl_read_file1_path.grid(column=1, row=5, sticky="W", columnspan=3)
        return filename1

    def returnfile1():
        return choose_file1()

    button_read_file1 = Button(mainpage, text="Durchsuchen...", command = returnfile1)
    button_read_file1.config(height = 1, width = 15)
    button_read_file1.grid(column=0, row=5, sticky="W")

    mainloop()

我需要更改为" print"文件choose_file1中函数gui(在函数main.py中定义)的文件名的字符串?

1 个答案:

答案 0 :(得分:3)

您的代码存在两个主要问题:

  • 函数gui没有明确的返回值。因此,当您调用它时,它会返回None

  • returnfile1返回的值(从choose_file1获得)不会存储在变量中,因此在函数退出时会丢失。

以下是快速修复以使您的代码正常工作(“main.py”中无需更改):

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
import os
import math
import sys

def gui():
    mainpage = Tk()
    # Variable to store the filename
    filename1 = "" 

    def choose_file1():
        # We want to use the same variable filename1 we declared above
        nonlocal filename1
        filename1 = filedialog.askopenfilename()
        lbl_read_file1_path = Label()
        lbl_read_file1_path.configure(text = filename1)
        lbl_read_file1_path.grid(column=1, row=5, sticky="W", columnspan=3)
        # No return statement is needed here

    # Function 'returnfile1' is not needed.

    button_read_file1 = Button(mainpage, text="Durchsuchen...", command = choose_file1)
    button_read_file1.config(height = 1, width = 15)
    button_read_file1.grid(column=0, row=5, sticky="W")

    mainloop()

    # Return the value of filename1
    return filename1