以下是代码:
import os
from tkinter.filedialog import askopenfilename
from tkinter import *
#~~~~ FUNCTIONS~~~~
def open_file_1():
global file_path_1
filename_1 = askopenfilename()
file_path_1 = os.path.dirname(filename_1) + filename_1
entry_1.delete(0, END)
entry_1.insert(0, file_path_1)
return file_path_1
def open_file_2():
global file_path_2
filename_2 = askopenfilename()
file_path_2 = os.path.dirname(filename_2) + filename_2
entry_3.delete(0, END)
entry_3.insert(0, file_path_2)
return file_path_2
def title_name_1():
global title_1
title_1=str(entry_4.get())
return title_1
def title_name_2():
global title_2
title_2=str(entry_5.get())
return title_2
def process_file(content):
print(file_path_1)
print(file_path_2)
print(title_1)
print(title_2)
#~~~~~~ GUI ~~~~~~~~
root = Tk()
root.title('Test Project')
root.geometry("698x220+350+200")
mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f3 = Frame(mf, width=600, height=250)
f3.pack(fill=X)
f4 = Frame(mf, width=600, height=250)
f4.pack(fill=X)
f5 = Frame(mf, width=600, height=250)
f5.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
file_path_1 = StringVar
file_path_2 = StringVar
title_1 = StringVar
title_2 = StringVar
Label(f1,text="Select File 1").grid(row=0, column=0, sticky='e')
Label(f3,text="Select File 2").grid(row=0, column=0, sticky='e')
Label(f4,text="Title1").grid(row=0, column=0, sticky='e')
Label(f5,text="Title2").grid(row=0, column=0, sticky='e')
entry_1 = Entry(f1, width=50, textvariable=file_path_1)
entry_1.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse", command=open_file_1).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
entry_3 = Entry(f3, width=50, textvariable=file_path_2)
entry_3.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f3, text="Browse", command=open_file_2).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
entry_4 = Entry(f4, width=50,textvariable=title_1)
entry_4.grid(row=0,column=1,padx=5,pady=2,sticky='we',columnspan=25)
entry_5 = Entry(f5, width=50,textvariable=title_2)
entry_5.grid(row=0,column=1,padx=5,pady=2,sticky='we',columnspan=25)
Button(f2, text="Submit", width=32, command=lambda: process_file(content)).grid(sticky='ew', padx=10, pady=70)
root.mainloop()
我想获取这4个字段(file_path_1
,file_path_2
,Title1
,Title2
)并存储它们以便可以用于进一步操作。我正在使用浏览以选择文件,用户将输入Title1和Title2的文本。我是新手,所以没有太多想法。
答案 0 :(得分:0)
使用StringVar()
,您不必要地使您的生活变得复杂。如果你将observer callbacks附加到它们上,StringVar最有用......
大部分时间用于Entry小部件,最好在使用之前使用.get()
方法获取内容:
def process_file():
# Get Entry box content
filename_1 = entry_1.get()
# Do something with it
print(filename_1)