从 askopenfilename() 返回一个字符串到输入框 [英] returning a string from askopenfilename() to a entry box

查看:23
本文介绍了从 askopenfilename() 返回一个字符串到输入框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多关于使用 askopenfilename() 的帖子,但是一旦我选择了所述文件,我似乎仍然无法找到任何帮助我在输入框中显示完整文件路径的内容.下面我已经包括了我离开的地方.

I have seen many postings on the use of askopenfilename(), however I still can't seem to find anything to help me display the full file path in an entry box once I have selected said file. below I have included where I have left off.

from tkinter import *
from tkinter.filedialog import askopenfilename

global a

def browse():
    a = askopenfilename(title='select new file')

root = Tk()

a = StringVar()

l = Label(root, text="new file: ")
l.pack()

e = Entry(root, width=25, textvariable=a)
e.pack()

b = Button(root, text="Browse", command=browse)
b.pack()


root.mainloop()

推荐答案

在您的 browse 函数中,局部变量 a 确实包含文件的完整路径.问题是您必须调用 StringVar 的 .set() 方法,您不能只分配给绑定到 StringVar 的变量.将 a = askopenfilename(title='select new file') 替换为 a.set(askopenfilename(title='select new file')),您将看到文件名出现在您界面的 StringVar 中.

Inside your browse function the local variable a does indeed contain the full path to your file. THe issue is that you have to call the StringVar's .set() method, you can't just assign to the variable you bound to the StringVar. Replace a = askopenfilename(title='select new file') with a.set(askopenfilename(title='select new file')) and you will see the filename appear in the StringVar in your interface.

请注意,您的程序结构不适合 GUI 界面任务,但我认为目前您的主要困难是学习使用原语.

Please note that your program is not well-structured for a GUI interface task, but I presume at present your major difficulty is learning to use the primitives.

这篇关于从 askopenfilename() 返回一个字符串到输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆