首页 > 解决方案 > Tkinter - 在函数中存储文件夹目录并调用它来更改目录

问题描述

我正在尝试用 tkinter 开发一个 GUI。我创建了一个函数(作为按钮)来浏览目录文件夹('输入文件夹')。我有一个链接到另一个按钮(“执行”)的例程,该按钮需要“输入文件夹”中的路径。

当我尝试将路径从“输入文件夹”传递到“执行”内的 os.chdir 时出现错误。示例如下:

import sys
import os
from tkinter import filedialog
from tkinter import *

window = Tk()

def Input():
    filename = filedialog.askdirectory()
    global filename

def Extraction():
    in_loc = filename
    os.chdir(in_loc)

btn = Button(window, text="Extract", bg="black", fg="white", command=Extraction)
btn.pack()

btn2 = Button(text="Input", command=Input).pack()

window.mainloop()

谁能重现这个并告诉我我在这里做错了什么?

谢谢 :)

标签: pythontkinteroperating-system

解决方案


试试这个:

import sys
import os
from tkinter import filedialog
from tkinter import *

filename = ''


def input_function():
    global filename

    filename = filedialog.askdirectory()


def extraction():
    global filename

    in_loc = filename
    os.chdir(in_loc)


window = Tk()

btn = Button(window, text="Extract", bg="black", fg="white", command=extraction)
btn.pack()

btn2 = Button(text="Input", command=input_function).pack()

window.mainloop()

推荐阅读