Python t按下一个按钮可更改2个条目
我正在用Tkinter构建一个简单的应用程序,它有两个浏览按钮。一个需要能够指向一个文件,另一个只指向一个文件夹。这是可行的,但当我使用其中一个按钮浏览时,它会填充两个条目。我是新来的,所以我真的不明白为什么 我正在使用此问题中的代码: 这是我的浏览功能:Python t按下一个按钮可更改2个条目,python,tkinter,Python,Tkinter,我正在用Tkinter构建一个简单的应用程序,它有两个浏览按钮。一个需要能够指向一个文件,另一个只指向一个文件夹。这是可行的,但当我使用其中一个按钮浏览时,它会填充两个条目。我是新来的,所以我真的不明白为什么 我正在使用此问题中的代码: 这是我的浏览功能: def open_file(type): global content global file_path global full_path if type == "file": filename = askopenfilename
def open_file(type):
global content
global file_path
global full_path
if type == "file":
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
file_path = os.path.dirname(filename)
entry.delete(0, END)
entry.insert(0, file_path+filename)
return content
elif type == "path":
full_path = askdirectory()
entry2.delete(0, END)
entry2.insert(0, full_path)
#return content
这是我的GUI代码:
mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack(fill=X)
Label(f1, text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')
Label(f2, text="Select target folder").grid(row=0, column=0, sticky='e')
entry = Entry(f1, width=50, textvariable=file_path)
entry2 = Entry(f2, width=50, textvariable=full_path)
entry.grid(row=0, column=1, padx=2, pady=2, sticky='we', columnspan=25)
entry2.grid(row=0, column=1, padx=(67, 2), pady=2, sticky='we', columnspan=25)
Button(f1, text="Browse", command=lambda: open_file("file")).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
Button(f2, text="Browse", command=lambda: open_file("path")).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
我怎样才能解决这个问题?谢谢注意,open\u file方法中的full\u path局部变量与全局变量同名
您应该对文本变量使用StringVar
更改文件路径和完整路径的初始化
而不是那些行:
entry.delete(0, END)
entry.insert(0, file_path+filename)
你可以简单地写:
full_path.set(file_path+filename)
与entry2相同,而不是:
elif type == "path":
full_path = askdirectory()
entry2.delete(0, END)
entry2.insert(0, full_path)
写:
elif type == "path":
full_path_dir = askdirectory()
full_path.set(full_path_dir)
elif type == "path":
full_path_dir = askdirectory()
full_path.set(full_path_dir)