【问题标题】:Need to return file path from function and pass it as argument to another function需要从函数返回文件路径并将其作为参数传递给另一个函数
【发布时间】:2021-09-28 20:53:27
【问题描述】:

所选文件的路径(存储在变量source_file中)必须从browseFiles()返回并作为参数传递给objdetect()

def browseFiles():
   source_file = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[('All Files', '.*')],parent=window)
   label_file_explorer.configure(text=""+source_file)

Python 3.8 (Tkinter) Project details

【问题讨论】:

  • 好的。你有什么问题或疑问?
  • return source_file 似乎是您问题的答案。你试过吗?

标签: python python-3.x tkinter


【解决方案1】:

这是一种方法:

def browseFiles():
   source_file = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[('All Files', '.*')],parent=window)
   label_file_explorer.configure(text=""+source_file)
   return source_file


def objdetect()
    file = browseFiles()

基本上只需使用return 语句返回一个值,然后将该函数分配给一个变量,它将被调用并将返回的值分配给变量

如果你只是想拥有一个全局值,你可以这样做:

def browseFiles():
   global source_file
   source_file = filedialog.askopenfilename(initialdir = "/", title = "Select a File", filetypes =[('All Files', '.*')],parent=window)
   label_file_explorer.configure(text=""+source_file)

现在变量source_file 将是全局变量,您可以在任何需要的地方引用它

【讨论】:

  • 有一个主函数调用browseFiles()objdetect()。根据您的建议,我了解到browseFiles() 函数将再次执行。我只是想使用保存在source_file 中的值而不调用该函数。有什么办法吗?
  • @KavyaPriya 好的,然后添加全局,我会更新
  • 谢谢@Matiiss!
猜你喜欢
  • 2021-04-21
  • 2021-02-08
  • 2021-12-02
  • 2021-04-10
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2013-11-19
相关资源
最近更新 更多