Tkinter 获取文件路径返回到主函数以使用并传递给其他函数

问题描述 投票:0回答:2

这是我当前的代码。

from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os

def main():
    path = open_file()
    print(path)
    
# Create an instance of tkinter frame
win = Tk()

# Set the geometry of tkinter frame
win.geometry("700x350")

def open_file():
   
   file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])
   if file:
      filepath = os.path.abspath(file.name)
      quit()
      print(filepath)
    
def quit():
    win.destroy()


# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)

# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)

win.mainloop()

if __name__ == '__main__':
    main()

我想创建一个简单的 GUI 来选择一个文件,然后在以后的其他功能中使用它的路径。在当前代码中,在 open_file 函数中窗口关闭后,文件路径可以正常打印,但仅当 print 语句位于函数中时才有效。如果我从那里删除它并想将其打印出来(只是为了测试)或进一步使用它将其传递给 main 中的其他函数,它似乎不起作用。没有错误,但也没有打印任何内容。有什么想法吗?

python function user-interface tkinter path
2个回答
1
投票

问题似乎是想要从使用按钮调用的函数返回一个值。这显然不可能。我发现的最简单的解决方案(无需更改太多代码结构)是使用全局变量

filepath
。现在您几乎可以在任何您想要的地方使用它。

此外,我已从您的

path = open_file()
函数中删除了
main()
,因为它是多余的。现在,仅在按下按钮时调用该函数,而不是在程序每次启动时调用。

from tkinter import * 
from tkinter import ttk, filedialog 
from tkinter.filedialog import askopenfile 
import os

def main():
    print(filepath)
    
# Create an instance of tkinter frame 
win = Tk()

# Set the geometry of tkinter frame 
win.geometry("700x350")

def open_file():
    file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])    
        if file:
            global filepath
            filepath = os.path.abspath(file.name)
            quit()

def quit():
    win.destroy()


# Add a Label widget 
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10)

# Create a Button 
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)

win.mainloop()

if __name__ == '__main__':
    main()

0
投票

上面的解决方案是最灵活的,但是如果您只需要为一个特定用途重新使用变量(例如设置另一个小部件的状态),还有一种方法可以直接在您的函数中执行此操作。 例如,您可以在

open_file()
:

中的打印语句上方包含此行
my_label["text"] = filepath

这将更改标签的文本(您可以在主体中创建标签,或者您可以更改现有的

label
)。您也可以这样做,例如带有“entry”小部件,但请注意语法会有所不同:

my_entry.insert("end", filepath)
© www.soinside.com 2019 - 2024. All rights reserved.