Python 在两个函数之间传递变量

时间:2021-02-04 13:16:11

标签: python arrays python-3.x variables tkinter

我正在尝试使用第一个函数打开文件,使用第二个函数打印文件内容。如果有人能帮我解决一些错误,那就太好了!

global strings

def open_file(): 
    file = askopenfile(parent=root,mode ='r', filetypes =[("All files", "*")])
    if file is not None: 
        content = file.read()
    strings = content.splitlines()
    return strings

def run_file(some_content):
    for i in some_content:
        print(bytes(i,"ascii"))
        time.sleep(1)

btn_upload = Button(root, text="UPLOAD",bg='#34495e', fg='white', command = lambda:open_file())
btn_upload.pack()
btn_run = Button(root, text="RUN",bg='#34495e', fg='white', command=lambda:run_file(strings))
btn_run.pack()

1 个答案:

答案 0 :(得分:0)

您需要将 global strings 放在 open_file() 函数中(实际上是在分配给该名称的任何函数中;从全局变量读取无需 global)。

strings = None

def open_file(): 
    global strings 
    # ...

def run_file():
    for i in strings:
        # ...

但是,出于可测试性等的考虑,我会避免使用全局变量,而可能只是将您的状态封装到一个类中。

相关问题